Mutex lock improvements

. 1  Import Time
 2  from Threading Import the Thread, Lock
 . 3  # define global variables NUM 
. 4 NUM = 0
 . 5  # Create a mutex 
. 6 Lock = Lock ()
 . 7  DEF test1 ():
 . 8      Global NUM
 . 9      '' ' 
10      in the two The lock method is called in each thread, then the two threads will rush to lock.
 11      If one party successfully locks, then the other party will block (wait) until the lock is unlocked
 12      '' ' 
13 is      for I in Range (100000 ):
 14          lock.acquire () # lock 
15         + =. 1 NUM
 16          lock.release () 
 . 17      Print ( ' test1 output NUM: ' , NUM)
 18 is  
. 19  DEF test2 ():
 20 is      Global NUM
 21 is      for I in Range (100000 ):
 22 is          lock.acquire ()   # lock 
23          num + = 1
 24          lock.release ()
 25      print ( ' test2 outputs num: ' , num)
 26  
27  if  __name__ == ' __main__ ':
28     t1 = Thread(target=test1)
29     t2 = Thread(target=test2)
30     t1.start()
31     t2.start()
32     t1.join()
33     t2.join()
1 test1 output num: 181043
 2 test2 output num: 200000

 

Guess you like

Origin www.cnblogs.com/monsterhy123/p/12682830.html
Recommended