zoukankan      html  css  js  c++  java
  • C++11多线程编程(八)——死锁问题

    一、死锁现象

    看到“死锁”二字,你是不是慌得不知所措。死锁,顾名思义就是这个锁死掉了,再也动不了了。那死锁是怎么产生的呢?当你对某个资源上锁后,却迟迟没有释放或者根本就无法释放,导致别的线程无法获得该资源的访问权限,进而程序无法运行下去,有点像是阻塞的现象。但是阻塞是一种正常现象,而死锁可以说是一种bug,必须要处理。

    那么我现在就举个死锁的例子,来分析分析。

     1 #include <iostream>
     2 #include <thread>
     3 #include <mutex>
     4 using namespace std;
     5  
     6 mutex mt1;
     7 mutex mt2;
     8 void thread1()
     9 {
    10     cout << "thread1 begin" << endl;
    11     lock_guard<mutex> guard1(mt1);
    12     this_thread::sleep_for(chrono::seconds(1));
    13     lock_guard<mutex> guard2(mt2);
    14     cout << "hello thread1" << endl;
    15 }
    16 void thread2()
    17 {
    18     cout << "thread2 begin" << endl;
    19     lock_guard<mutex> guard1(mt2);
    20     this_thread::sleep_for(chrono::seconds(1));
    21     lock_guard<mutex> guard2(mt1);
    22     cout << "hello thread2" << endl;
    23 }
    24  
    25 int main()
    26 {
    27     thread t1(thread1);
    28     thread t2(thread2);
    29     t1.join();
    30     t2.join();
    31     cout << "thread end" << endl;
    32     return 0;
    33 }

    二、死锁分析

    因为程序运行的是非常快的,所以为了产生死锁现象,我们各自休眠了1秒。

    运行以上程序可以发现,程序在输出完“thread1 beginthread2 begin”后,就卡在那里,程序运行可能发生了以下这种情况:

    1 thread1 thread2
    2 mt1.lock() mt2.lock()
    3 //死锁 //死锁
    4 mt2.lock() mt1.lock()

    thread1中的mt2在等待着thread2的mt2释放锁,而thead2中mt1却也在等待着thread1的mt1释放锁,互相都在等待着对方释放锁,进而产生了死锁。必须强调的是,这是一种bug,必须避免。那么如何避免这种情况呢?

    三、死锁解决

    1、每次都先锁同一个锁

    比如像上面thread1和thread2线程,我们每次都先锁mt1,在锁mt2,就不会发生死锁现象。

    2、给锁定义一个层次的属性,每次按层次由高到低的顺序上锁,这个原理也是每次都先锁同一个锁。

    C++标准库中提供了std::lock()函数,能够保证将多个互斥锁同时上锁。

    std::lock(mt1, mt2);

    那么既然在最前面就已经上锁了,后面就不需要上锁了,而C++标准库并没有提供std::unlock()的用法,所以还是需要用到lock_guard,但是需要修改一点。加个std::adopt_lock就可以了。

    1 lock_guard<mutex> guard1(mt1, adopt_lock);
    2 lock_guard<mutex> guard2(mt2, adopt_lock);

    这个表示构造函数的时候不要给我上锁,到析构的时候你要记得给我解锁。

    这个就是死锁的一些解决方法,同时大家一定要记得尽量不要一段定义域内多次使用互斥锁,如果不可避免的要使用,一定要记得给锁定义顺序,或者使用要使用std::lock()上锁。

    更多精彩内容,请关注同名公众:一点月光(alittle-moon)

  • 相关阅读:
    mysql 下 计算 两点 经纬度 之间的距离
    富爸爸财务自由之路
    Ubuntu16.04忘记MySQL5.7的root用户密码之解决方案
    Windowns下code: command not found
    Linux下CRMEB环境搭建
    PHP无法使用curl_init()函数
    请在mysql配置文件修sql-mode或sql_mode为NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
    apache不能解析php之解决办法
    windows上hexo: command not found
    SyntaxError: Non-ASCII character 'æ' in file csdn.py on line 7, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
  • 原文地址:https://www.cnblogs.com/kiwiblog/p/14206153.html
Copyright © 2011-2022 走看看