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

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

死锁概念

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

代码如下:

''' 

Created on 2012-9-8 

 

@author: walfred 

@module: thread.TreadTest5 

'''   

import threading  

 

counterA = 0  

counterB = 0  

 

mutexA = threading.Lock()  

mutexB = threading.Lock()  

 

class MyThread(threading.Thread):  

    def __init__(self):  

        threading.Thread.__init__(self)  

 

    def run(self):  

        self.fun1()  

        self.fun2()  

 

    def fun1(self):  

        global mutexA, mutexB  

        if mutexA.acquire():  

            print "I am %s , get res: %s" %(self.name, "ResA")  

 

            if mutexB.acquire():  

                print "I am %s , get res: %s" %(self.name, "ResB")  

                mutexB.release()  

 

        mutexA.release()   

 

    def fun2(self):  

        global mutexA, mutexB  

        if mutexB.acquire():  

            print "I am %s , get res: %s" %(self.name, "ResB")  

 

            if mutexA.acquire():  

                print "I am %s , get res: %s" %(self.name, "ResA")  

                mutexA.release()  

 

        mutexB.release()   

 

if __name__ == "__main__":  

    for i in range(0, 100):  

        my_thread = MyThread()  

        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年提出的银行家算法。