C++多线程学习笔记003lock_guard和unique_lock

C++多线程学习笔记003lock_guard和unique_lock

引言

使用mutex.lock()和mutex.unlock()可以用来完成基本的互斥锁操作,想用高级一点的lock操作可以用lock_guard和unique_lock

lock_guard

lock_guard在其构造函数中会对其传入的mutex实参进行自动加锁,在其析构函数中会对其传入的mutex实参进行自动unlock,所以可以用lock_guard搭配作用域,完成自动的加锁解锁。

#include<iostream>
#include<thread>
#include<unistd.h>
#include<mutex>
std::mutex mtx;

int num {0};

void func1(){
    for(size_t i = 0; i < 100; i++ ){
        std::lock_guard<std::mutex> lck_gu(mtx);
        num++;
    }
}

int main(){

    std::thread thread1(func1);
    std::thread thread2(func1);
    thread1.join();
    thread2.join();
    std::cout <<"num = " << num << std::endl;
    return 0;
}
// g++ ./XXX.cpp -o ./XXX -pthread

unique_lock

相比于lock_guard,unique_lock能实现更复杂的操作,比如阻塞的延时加锁,定时加锁等

#include<iostream>
#include<thread>
#include<unistd.h>
#include<mutex>
std::timed_mutex mtx;

int num {0};

void func1(){
    for(size_t i = 0; i < 3; i++ ){
        std::unique_lock<std::timed_mutex> unlck(mtx,std::defer_lock);//创造unique_lock但不加锁
        if (unlck.try_lock_for(std::chrono::seconds(1))){
            std::this_thread::sleep_for(std::chrono::seconds(1));
            num++;
        }
        
    }
}

int main(){

    std::thread thread1(func1);
    std::thread thread2(func1);
    thread1.join();
    thread2.join();
    std::cout <<"over" << std::endl;
    std::cout <<"num = " << num << std::endl;
    return 0;
}
// g++ ./XXX.cpp -o ./XXX -pthread
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值