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
相关推荐
yngsqq8 分钟前
031集——文本文件按空格分行——C#学习笔记
笔记·学习·c#
sukalot11 分钟前
windows C++-windows C++-使用任务和 XML HTTP 请求进行连接(二)
c++·windows
qianbo_insist34 分钟前
simple c++ 无锁队列
开发语言·c++
zengy535 分钟前
Effective C++中文版学习记录(三)
数据结构·c++·学习·stl
cyt涛44 分钟前
MyBatis 学习总结
数据库·sql·学习·mysql·mybatis·jdbc·lombok
Willliam_william1 小时前
SystemC学习(1)— SystemC安装与HelloWorld
学习
sealaugh321 小时前
aws(学习笔记第一课) AWS CLI,创建ec2 server以及drawio进行aws画图
笔记·学习·aws
布丁不叮早起枣祈1 小时前
10.5学习
学习
CXDNW1 小时前
【网络篇】计算机网络——应用层详述(笔记)
服务器·笔记·计算机网络·http·web·cdn·dns
向上的车轮1 小时前
Django学习笔记五:templates使用详解
笔记·学习·django