zthread学习 实例十二 线程间的协助(三)——死锁

因为线程可以变为阻塞,且因为对象可以拥有互斥锁,这些锁能够阻止线程在锁被释放之前访问这个对象。所以就有可能出现这种情况,某个线程在等待另一个线程而第2个线程又在等待别的线程,以此类推,直到这个链上的最后一个线程回头等待第1个线程。这样就会得到一个由互相等待的线程构成的连续的循环,而使任何线程都不能运行——死锁。死锁的过程是很难重现的,调试的难点。

下面看一个经典的死锁问题——哲学家聚餐。

 

 

[cpp]  view plain copy
  1. #include "stdafx.h"  
  2. #include "zthread/Mutex.h"  
  3. #include "zthread/CountedPtr.h"  
  4. #include "zthread/Runnable.h"  
  5. #include "zthread/Condition.h"  
  6. #include "zthread/Guard.h"  
  7. #include "Display.h"  
  8. #include <iostream>  
  9. #include <ctime>  
  10. using namespace ZThread;  
  11. using namespace std;  
  12. //(一根)筷子  
  13. class Chopstick  
  14. {  
  15. public:  
  16.     Chopstick() : notTaken(Lock), taken(false){}  
  17.       
  18.     //拿起筷子  
  19.     void Take()  
  20.     {  
  21.         Guard<Mutex> g(Lock);  
  22.           
  23.         //如果筷子此时已被拿起,再被拿起时,必须等待  
  24.         while(taken == true)  
  25.             notTaken.wait();  
  26.         taken = true;  
  27.     }  
  28.       
  29.     //放下筷子  
  30.     void Drop()  
  31.     {  
  32.         Guard<Mutex> g(Lock);  
  33.           
  34.         taken = false;  
  35.           
  36.         //唤醒要拿起它的线程  
  37.         notTaken.signal();   
  38.     }  
  39. private:  
  40.     Mutex       Lock;  
  41.     Condition   notTaken;  
  42.     bool        taken;  
  43. };  
  44. class Philosopher : public Runnable  
  45. {  
  46. public:  
  47.     Philosopher(Chopstick& l, Chopstick& r, int idn, int ponder, CountedPtr<Display>& disp):  
  48.     left(l), right(r), id(idn), ponderFactor(ponder), display(disp)  
  49.     {  
  50.       
  51.     }  
  52.       
  53.     virtual void run()  
  54.     {  
  55.         try  
  56.         {  
  57.             while (!Thread::interrupted())  
  58.             {  
  59.                 output("Think!");  
  60.                 Thread::sleep(randSleepTime());  
  61.                   
  62.                 output("grabbing right");  
  63.                 right.Take();  
  64.                   
  65.                 output("grabbing left");  
  66.                 left.Take();  
  67.                   
  68.                   
  69.                 output("Eatting!");  
  70.                 Thread::sleep(randSleepTime());  
  71.                   
  72.                 right.Drop();  
  73.                 left.Drop();  
  74.             }  
  75.         }  
  76.         catch (Interrupted_Exception& e)  
  77.         {  
  78.             cerr << " Jarry :" << e.what() <<endl;  
  79.         }  
  80.     }  
  81.     friend ostream& operator <<(ostream& os, const Philosopher& p)  
  82.     {  
  83.         return os << "Philosopher : " << p.id;  
  84.     }  
  85.       
  86. private:  
  87.     Chopstick& left;  
  88.     Chopstick& right;  
  89.       
  90.     int id;  
  91.     int ponderFactor;  
  92.       
  93.     CountedPtr<Display> display;  
  94.       
  95.     int randSleepTime()  
  96.     {  
  97.         if (ponderFactor == 0)  return 0;  
  98.           
  99.         return rand() / (RAND_MAX / ponderFactor) * 250;  
  100.     }  
  101.       
  102.     void output(string str)  
  103.     {  
  104.         ostringstream os;  
  105.         os << *this << " : " << str <<endl;  
  106.           
  107.         display->OutPut(os);  
  108.     }  
  109. };  
  110. int _tmain(int argc, _TCHAR* argv[])   
  111. {  
  112.     srand((unsigned int)time(0));  
  113.       
  114.     const int count = 5;  
  115.       
  116.     int pender =  0;  
  117.       
  118.     try  
  119.     {  
  120.         CountedPtr<Display> disp(new Display);  
  121.           
  122.         ThreadedExecutor executor;  
  123.           
  124.         Chopstick chopstick[count];  
  125.           
  126.         for (int i = 0; i < count; i ++)  
  127.         {  
  128.             //会出现死锁,是因为出现了循环等待  
  129.             //executor.execute(new Philosopher(chopstick[i], chopstick[(i + 1) % count], i, pender, disp));  
  130.               
  131.             //打破发生死锁的第4个条件(循环等待)  
  132.             if (i < count - 1)  
  133.                 executor.execute(new Philosopher(chopstick[i], chopstick[(i + 1)], i, pender, disp));  
  134.             else  
  135.                 executor.execute(new Philosopher(chopstick[0], chopstick[i], i, pender, disp));  
  136.         }  
  137.         cin.get();  
  138.         executor.interrupt();  
  139.         executor.wait();  
  140.           
  141.         cin.get();  
  142.           
  143.     }  
  144.     catch (Synchronization_Exception& e)  
  145.     {  
  146.         cerr << " Jarry main " << e.what() <<endl;  
  147.     }  
  148.     return 0;  
  149. }  
 

如果在某一个时间点上所有的哲学家同时试图进餐,拿起同一侧的一根筷子,并且等待紧挨着他们的哲学家放下筷子,这样程序将会死锁。

 

 

 

同时满足以下4种条件,死锁就会发生:

1、相互排斥。线程使用的资源至少有一个必须是不可共享的。在这种情况下,一根筷子一次只能被一个哲学家使用。

2、至少有一个线程必须持有某一种资源,并且同时等待获得正在被另外的线程所持有的资源。也就是说要发生死锁一个哲学家必须持有一根筷子并且等待另一根筷子。

3、不能以抢占的方式剥夺一个线程的资源。所有线程只能把释放的资源作为一个正常事件。他们不会从别的哲学家手中抢夺筷子。

4、出一个循环等待。一个线程等待另外的线程所持有的资源,而这个等待的线程又等待另一个线程所持有的资源,以此类推直到某个线程去等待第一个线程所持有的资源。例子中每一个哲学家总是试图先得到右边的筷子,而后得到左边的筷子,所以发生了循环等待。

 

避免死锁只要打破以上四个条件中的一个就可以了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值