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
#include
#include
#include
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
#include
#include
#include
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

你可能感兴趣的:(c++,学习,笔记)