A big lock in a small lock.
Import Threadingimport timedef run1 (): print ("Grab the first part data") Lock.acquire () global num num + = 1 lock.release () return numdef run2 (): print ("Grab the second part data") Lock.acquire () Global num2 num2 + = 1 lock.release () return num2def run3 (): lock.acquire () res = RUN1 () Print ('--------between run1 and run2-----') res2 = run2 () lock.release () print (res, res2) if __name__ = = ' __main__ ': num, num2 = 0, 0 lock = Threading. Lock () for I in range: t = Threading. Thread (TARGET=RUN3) T.start () while Threading.active_count ()! = 1: print (Threading.active_count ()) Else: print ('----All threads do---') print (num, num2)
Process sharing:
1. Start 10 threads, and each thread executes RUN3.
2, Run3 First add a lock, and then execute the RUN1.
3, RUN1 also added a lock, after the completion of the calculation to unlock the return data. Execute run2.
4, Run2 also added a lock, after the completion of the calculation to unlock the print run1,run2 return value.
5, the final printing num1, num2.
It is important to note that there are two locks during execution, one run3, one run1 or run2.
Operation Result:
1111111111111111# program into the dead loop
The reason for the dead loop is that when the key is unlocked it is wrong to cause the process to fall out and the deadlock is to use a recursive lock.
Threading. Lock () changed to threading. Rlock ()
Import Threadingimport timedef run1 (): print ("Grab the first part data") Lock.acquire () global num num + = 1 lock.release () return numdef run2 (): print ("Grab the second part data") Lock.acquire () Global num2 num2 + = 1 lock.release () return num2def run3 (): lock.acquire () res = RUN1 () Print ('--------between run1 and run2-----') res2 = run2 () lock.release () print (res, res2) if __name__ = = ' __main__ ': num, num2 = 0, 0 lock = Threading. Rlock () for I in range (1): t = Threading. Thread (TARGET=RUN3) T.start () while Threading.active_count ()! = 1: print (Threading.active_count ()) Else: print ('----All threads do---') print (num, num2)
Run results
Grab the first part data--------between RUN1 and run2-----Grab the second part data1 1----All threads done---1 1
Implementation principle:
When unlocking, look for the corresponding key.
Python recursive lock