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
相关推荐
m0_5713728225 分钟前
嵌入式ARM架构学习2——汇编
arm开发·学习
大筒木老辈子1 小时前
Linux笔记---封装套接字
笔记
AlexMercer10121 小时前
[前端]1.html基础
前端·笔记·学习·html
晚云与城1 小时前
今日分享:C++ Stack和queue(栈与队列)
开发语言·c++
楚肽生物小敏1 小时前
Cy3-Tyramide,Cyanine 3 Tyramide; 174961-75-2
笔记
bikong72 小时前
一种高效绘制余晖波形的方法Qt/C++
数据库·c++·qt
深耕AI2 小时前
【MFC文档与视图结构:数据“仓库”与“橱窗”的梦幻联动 + 初始化“黑箱”大揭秘!】
c++·mfc
健康平安的活着3 小时前
langchain4j笔记篇(阳哥)
笔记
一川月白7093 小时前
51单片机---硬件学习(跑马灯、数码管、外部中断、按键、蜂鸣器)
单片机·学习·51单片机·外部中断·蜂鸣器·数码管·跑马灯
励志不掉头发的内向程序员3 小时前
STL库——二叉搜索树
开发语言·c++·学习