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
相关推荐
远离UE41 天前
UE5 compute shader 原子加
开发语言·c++·ue5
C+-C资深大佬1 天前
C++ 显式类型转换详解:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
心中有国也有家1 天前
AtomGit Flutter 鸿蒙客户端: ChangeNotifier 模式
学习·flutter·华为·harmonyos
luj_17681 天前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
取地址符1 天前
C++学习笔记(基于learn-cxx)(1)
c++·经验分享·笔记·学习
思麟呀1 天前
C++17(三)if constexpr+折叠表达式
开发语言·c++
ysa0510301 天前
【板子】ST表
c++·笔记·算法·板子
恣逍信点1 天前
主观是客观的聚焦
人工智能·学习·程序人生·生活·业界资讯·交友·哲学
CHHH_HHH1 天前
【C++11】深入解析C++可变参数模板
开发语言·c++·算法·stl·c++11
十五年专注C++开发1 天前
fatal error C1189: #error: WinSock.h has already been included 的解决方案
c++·socket·boost