Python multi threaded programming (v) : deadlock formation

  • 2020-05-05 11:25:33
  • OfStack

In the previous article, Python: multi-threaded programming using threading module 4 [using Lock mutex] we have already started to cover how to use mutex to protect our common resources, now consider the following situation

If there are multiple common resources, what is the problem when threads share multiple resources, if each thread has a share of the resource and is waiting for the other's resource at the same time?

deadlock concept

So-called deadlock: refers to two or more processes in the process of execution, due to the competition for resources caused by a phenomenon of waiting for each other, if there is no external force, they will not be able to move forward. At this point the system is said to be in a deadlock state or the system has created a deadlock. These processes that are always waiting for each other are called deadlock processes. Because resource occupancy is mutually exclusive, when a process makes a request for resources, the process concerned will never be able to allocate the necessary resources without external assistance and cannot continue to run, which creates a special deadlock.


'''
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()

The code shows two functions of a thread that acquire a competing resource and then acquire another competing resource. The result is


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

As you can see, the program is already hanging there, which we call a deadlock.

avoid deadlocks

The main method to avoid deadlock is to allocate resources correctly and orderly. The most representative algorithm to avoid deadlock is Dijkstra E.W proposed the banker algorithm in 1968.


Related articles: