前一篇文章Python:使用threading模块实现多线程编程四[使用Lock互斥锁]我们已经开始涉及到如何使用互斥锁来保护我们的公共资源了,现在考虑下面的情况--

        如果有多个公共资源,在线程间共享多个资源的时候,如果两个线程分别占有一部分资源并且同时等待对方的资源,这会引起什么问题?

死锁概念

        所谓死锁: 是指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程。 由于资源占用是互斥的,当某个进程提出申请资源后,使得有关进程在无外力协助下,永远分配不到必需的资源而无法继续运行,这就产生了一种特殊现象死锁。

Python代码

  1. '''''
  2. Created on 2012-9-8
  3. @author: walfred
  4. @module: thread.TreadTest5
  5. '''
  6. import threading 
  7. counterA = 0
  8. counterB = 0
  9. mutexA = threading.Lock() 
  10. mutexB = threading.Lock() 
  11. class MyThread(threading.Thread): 
  12. def __init__(self): 
  13.         threading.Thread.__init__(self) 
  14. def run(self): 
  15. self.fun1() 
  16. self.fun2() 
  17. def fun1(self): 
  18. global mutexA, mutexB 
  19. if mutexA.acquire(): 
  20. print "I am %s , get res: %s" %(self.name, "ResA") 
  21. if mutexB.acquire(): 
  22. print "I am %s , get res: %s" %(self.name, "ResB") 
  23.                 mutexB.release() 
  24.         mutexA.release()  
  25. def fun2(self): 
  26. global mutexA, mutexB 
  27. if mutexB.acquire(): 
  28. print "I am %s , get res: %s" %(self.name, "ResB") 
  29. if mutexA.acquire(): 
  30. print "I am %s , get res: %s" %(self.name, "ResA") 
  31.                 mutexA.release() 
  32.         mutexB.release()  
  33. if __name__ == "__main__": 
  34. for i in range(0, 100): 
  35.         my_thread = MyThread() 
  36.         my_thread.start()     

        代码中展示了一个线程的两个功能函数分别在获取了一个竞争资源之后再次获取另外的竞争资源,我们看运行结果:

I am Thread-1 , get res: ResA
I am Thread-1 , get res: ResB
I am Thread-2 , get res: ResAI am Thread-1 , get res: ResB

        可以看到,程序已经挂起在那儿了,这种现象我们就称之为”死锁“。

避免死锁

        避免死锁主要方法就是:正确有序的分配资源,避免死锁算法中最有代表性的算法是Dijkstra E.W 于1968年提出的银行家算法