C++多线程学习笔记002多线程互斥锁基本操作和死锁

C++多线程学习笔记002多线程互斥锁基本操作和死锁

引言

C++中要注意线程安全,多个线程不能同时读写一个变量,这时就需要互斥锁来保证某个变量同一时间只能被某个一个线程访问

实列代码

cpp 复制代码
#include<iostream>
#include<thread>
#include<unistd.h>
#include<mutex>
std::mutex mtx;
int num;
void count_up(){
    for(size_t i = 0; i < 10000; i++ ){
        mtx.lock();
        num += 1;
        mtx.unlock();
    }

}


int main(){

    std::thread thread_count_up1(count_up);
    std::thread thread_count_up2(count_up);

    thread_count_up1.join();
    thread_count_up2.join();
    std::cout<<"num = "<<num<<std::endl;
    return 0;
}
// g++ ./XXX.cpp -o ./XXX -pthread

1, 使用std::mutex创建互斥锁

2, 注意互斥锁的逻辑,如果逻辑有问题,会出现"你等我,我等你 "的死锁问题

死锁示例

cpp 复制代码
#include<iostream>
#include<thread>
#include<unistd.h>
#include<mutex>
std::mutex mtx1;
std::mutex mtx2;
// //下面这样写会死锁
// void func1(){
//     for(size_t i = 0; i < 10000; i++ ){
//         mtx1.lock();
//         mtx2.lock();
//         mtx1.unlock();
//         mtx2.unlock();
//     }
// }
// void func2(){
//     for(size_t i = 0; i < 10000; i++ ){
//         mtx2.lock();
//         mtx1.lock();
//         mtx2.unlock();
//         mtx1.unlock();
//     }
// }
// //解决死锁方式1
// void func1(){
//     for(size_t i = 0; i < 10000; i++ ){
//         mtx1.lock();
//         mtx1.unlock();
//         mtx2.lock();
//         mtx2.unlock();
//     }
// }
//解决死锁方式2
void func1(){
    for(size_t i = 0; i < 10000; i++ ){
        mtx1.lock();
        mtx2.lock();
        mtx1.unlock();
        mtx2.unlock();
    }
}
void func2(){
    for(size_t i = 0; i < 10000; i++ ){
        mtx1.lock();
        mtx2.lock();
        mtx1.unlock();
        mtx2.unlock();
    }
}

int main(){

    std::thread thread1(func1);
    std::thread thread2(func2);

    thread1.join();
    thread2.join();
    std::cout<<"over"<<std::endl;
    return 0;
}
// g++ ./XXX.cpp -o ./XXX -pthread
相关推荐
charade3124 小时前
【C语言】内存分配的理解
c语言·开发语言·c++
yuhouxiyang6 小时前
学习海康VisionMaster之路径提取
学习·计算机视觉
雾削木7 小时前
mAh 与 Wh:电量单位的深度解析
开发语言·c++·单片机·嵌入式硬件·算法·电脑
PLUS_WAVE8 小时前
CogCoM: A Visual Language Model with Chain-of-Manipulations Reasoning 学习笔记
学习·语言模型·大模型·cot·vlm·推理模型·reasoning
绵绵细雨中的乡音8 小时前
Linux进程学习【环境变量】&&进程优先级
linux·运维·学习
贺函不是涵8 小时前
【沉浸式求职学习day27】
学习
努力奋斗的小杨8 小时前
学习MySQL的第十二天
数据库·笔记·学习·mysql·navicat
枫叶20009 小时前
OceanBase数据库-学习笔记1-概论
数据库·笔记·学习·oceanbase
Ethon_王9 小时前
走进Qt--工程文件解析与构建系统
c++·qt
一点.点9 小时前
李沐动手深度学习(pycharm中运行笔记)——04.数据预处理
pytorch·笔记·python·深度学习·pycharm·动手深度学习