zoukankan      html  css  js  c++  java
  • C++中 锁的使用 互斥锁:std::mutex std::lock_guard std::unique_lock ,读写锁使用shared_mutex ,条件变量使用std::condition_variable类

    转载:https://blog.csdn.net/faihung/article/details/88411839

      https://blog.csdn.net/XindaBlack/article/details/105915806

    简介:std::mutex:互斥量,C++11中与mutex相关的类(包括锁类型)和函数都声明在<mutex>头文件中。(C++官网

    读写锁:后续补充

    自旋锁:后续补充

    <mutex> 头文件介绍

    mutex系列类(四种):

    • std::mutex:最基本的mutex类
    • std::recursive_mutex:递归mutex类
    • std::timed_mutex:定时mutex类
    • std::recursive_timed_mutex:递归定时mutex类

    lock类(两种):

    • std::lock_guard:与mutex RAII 相关,方便线程对互斥量上锁
    • std::unique_lock:与mutex RAII相关,方便线程对互斥量上锁,但提供了更好的上锁和解锁控制

    其他类型:

    • std::once_flag
    • std::adopt_lock_t
    • std::defer_lock_t
    • std::try_to_lock_t

    函数:

    • std::try_lock:尝试同时对多个互斥量上锁
    • std::lock:可以同时对多个互斥量上锁
    • std::call_once:如果多个线程需要同时调用某个函数,call_once可以保证多个线程对该函数只调用一次

    std::mutex介绍

    std::mutex是C++11中最基本的互斥量,std::mutex对象提供了独占所有权的特性——既不支持递归地对std::mutex上锁,而std::recursive_lock可以递归地对互斥量对象上锁。

    std::mutex的成员函数

    • 构造函数,std::mutex不允许拷贝构造函数,也不允许move拷贝,最初产生的mutex对象是处于unlocked状态的。
    • lock(),调用线程将锁住该互斥量。线程调用该函数会发生下面3中情况。(1)如果该互斥量当前没有被锁住,则调用线程将该互斥量锁住,知道调用unlock之前,该线程会一直拥有该锁。(2)如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住。(3)如果当前互斥量被当前调用线程锁住,则会产生死锁。(第三条应该是递归锁要解决的问题)
    • unlock(),解锁,释放对互斥量的所有权。
    • try_lock(),尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会阻塞。线程调用该函数也会出现下面3中情况。(1)如果当前互斥量没有被其他线程占有,则该线程锁住互斥量,直到该线程调用unlock释放互斥量。(3)如果当前互斥量被当前调用线程锁住,则会产生死锁。

    注意:在编译的时候可能会报 underfined  reference to ‘pthread_create’错误,这个在编译选项中加 -g -lpthread 既可。原因

    具体编译命令:

    g++ -std=c++11 lock.cpp -g -lpthread
    

    case 1:mutex 

    #include <iostream>
    #include <thread>
    #include <mutex>
    
    using namespace std;
    
    volatile int counter(0);
    mutex mtx;
    
    void attempt_10k_increases() {
        for (int i = 0; i < 10000; ++i) {
            if (mtx.try_lock()) {
                ++counter;
                mtx.unlock();
            }
        }
    }
    
    int main(int argc, const char* argv[]) {
        thread threads[10];
        for (int i=0; i < 10; ++i) {
            threads[i] = thread(attempt_10k_increases);
        }
    
        for (auto& th : threads) {
            th.join();
        }
    
        cout << counter << " successful increases of the counter." << endl;
    
        return 0;
    }

    std::recursive_mutex介绍

    std::recursive_mutex与std::mutex一样,也是一种可以被上锁的对象,但是和std::mutex不同的是,std::recursive_mutex允许同一个线程对互斥量多次上锁(即递归上锁),来获取对互斥量对象的多层所有权,std::recursive_mutex释放互斥量时需要调用与该锁层次深度相同次数的unlock(),可理解为lock()次数 和 unlock()次数相同,除此之外,std::recursive_mutex的特性和std::mutex大致相同。

    std::timed_mutex 介绍

    std::timed_mutex 比 std::mutex多了两个成员函数,try_lock_for(), try_lock_until()。

    try_lock_for函数接受一个时间范围,表示在这一段时间范围之内线程如果没有获得锁则被阻塞住(与std::mutex的try_lock不同, try_lock如果被调用时没有获得锁则直接返回false),如果在此期间其他线程释放了锁,则该线程可以获得互斥量的锁,如果超时(即在指定时间内还是没有获得锁),则返回false。

    try_lock_until函数则接受一个时间点作为参数,在指定时间点未到来之前线程如果没有获得锁则被阻塞住,如果在此期间其他线程释放了锁,则该线程获得互斥量的锁,如果超时(即在指定时间内还没有获得锁),则返回false。

    case 2 :timed_mutex

    #include <iostream>
    #include <chrono>
    #include <thread>
    #include <mutex>
    
    using namespace std;
    
    timed_mutex mtx;
    
    void  fireworks() {
        while (!mtx.try_lock_for(chrono::milliseconds(200))) {
            cout << "-" ;
        }
    
        this_thread::sleep_for(chrono::milliseconds(1000));
        cout << "*"  <<  endl;
    
        mtx.unlock();
    }
    
    int main() {
        thread threads[10];
        for (int i = 0; i <10;  ++i) {
            threads[i] = thread(fireworks);
        }
    
        for (auto &th : threads)
             th.join();
    
        return 0;    

    std::recursive_timed_mutex 介绍

    和std::recursive_mutex 与 std::mutex 的关系一样,可以通过std::timed_mutex推到。

    std::lock_guard介绍

    与mutex RAI相关,方便线程对互斥量上锁。

    case 3:lock_guard

    #include <iostream>       // std::cout
    #include <thread>         // std::thread
    #include <mutex>          // std::mutex, std::lock_guard
    #include <stdexcept>      // std::logic_error
     
    std::mutex mtx;
     
    void print_even (int x) {
        if (x%2==0) std::cout << x << " is even
    ";
        else throw (std::logic_error("not even"));
    }
     
    void print_thread_id (int id) {
        try {
            // using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
            std::lock_guard<std::mutex> lck (mtx);
            print_even(id);
        }
        catch (std::logic_error&) {
            std::cout << "[exception caught]
    ";
        }
    }
     
    int main ()
    {
        std::thread threads[10];
        // spawn 10 threads:
        for (int i=0; i<10; ++i)
            threads[i] = std::thread(print_thread_id,i+1);
     
        for (auto& th : threads) th.join();
     
        return 0;

     

    std::unique_lock介绍

    case 4 :unique_lock

    #include <iostream>       // std::cout
    #include <thread>         // std::thread
    #include <mutex>          // std::mutex, std::unique_lock
     
    std::mutex mtx;           // mutex for critical section
     
    void print_block (int n, char c) {
        // critical section (exclusive access to std::cout signaled by lifetime of lck):
        std::unique_lock<std::mutex> lck (mtx);
        for (int i=0; i<n; ++i) {
            std::cout << c;
        }
        std::cout << '
    ';
    }
     
    int main ()
    {
        std::thread th1 (print_block,50,'*');
        std::thread th2 (print_block,50,'$');
     
        th1.join();
        th2.join();
     
        return 0;

    unique_lock和lock_guard的区别:

    简单来说就是:unique_lock支持直接加锁:unique_lock<mutex> lk(mtx);也支持lock和unlock函数。而lock_guard支持lock_guard<mutex> lk(mtx);

    https://blog.csdn.net/qq_37233607/article/details/80159873

  • 相关阅读:
    类型“System.Windows.Markup.IUriContext”在未被引用的程序集中定义 解决办法
    c# 根据文件流查看文件真实格式
    WPF ListBoxItem 使用Command命令添加双击事件
    MVVM 在使用 ItemsSource 之前,项集合必须为空
    WPF 自定义TextBox,可控制键盘输入内容
    百万数据如何在前端快速流畅显示?
    NodeJS npm 包装包失败的解决方案
    node.js express 4.x 安装指南(Express不是内部或外部命令解决方案)
    IIS8 不能在此路径中使用此配置节。如果在父级别上锁定了该节
    Npoi操作excel
  • 原文地址:https://www.cnblogs.com/xiaohaigegede/p/13588434.html
Copyright © 2011-2022 走看看