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

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

引言

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

实列代码

#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, 注意互斥锁的逻辑,如果逻辑有问题,会出现”你等我,我等你“的死锁问题

死锁示例

#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
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值