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
相关推荐
重启的码农2 分钟前
KCP源码解析 (6) 拥塞控制(Congestion Control)
c++·网络协议
小蛋编程12 分钟前
【算法-图论】图的存储
c++·算法·图论
楼田莉子31 分钟前
C++学习之继承
开发语言·c++·学习·visual studio
Jay Kay1 小时前
从0到1理解大语言模型:读《大语言模型:从理论到实践(第2版)》笔记
人工智能·笔记·语言模型
BS_Li1 小时前
C++继承
c++·继承
KD杜小帅1 小时前
2025年Solar应急响应公益月赛-7月笔记ing
笔记
怀旧,1 小时前
【C++】1. C++基础知识
开发语言·c++·算法
姜行运2 小时前
数据结构【红黑树】
数据结构·c++·c#
君鼎2 小时前
Effective C++ 条款10:令operator=返回一个reference to *this
c++
鬼魅-95272 小时前
VS+Qt中使用QCustomPlot绘制曲线标签(附源码)
c++·qt