fromThreadingImportThread, LockImportTimen= 100deftask ():GlobalN#Mutex.acquire ()temp =N Time.sleep (0.1) n= Temp-1#mutex.release ()if __name__=='__main__': #mutex = Lock ()t_l = [] forIinchRange (100): T= Thread (target=Task) T_l.append (t) t.start () forTinchT_l:t.join ()Print('Master', N)
Operation Result:
Main 99
View Code
A mutex is added:
#Mutex fromThreadingImportThread, LockImportTimen= 100deftask ():Globaln mutex.acquire () temp=N Time.sleep (0.1) n= Temp-1mutex.release ()if __name__=='__main__': Mutex=The difference between lock () # and child processes is that the child thread shares the memory space within the process, so there is no need to pass the lock to the thread. All threads within a process use the same lock.
# When the process is open, the data between the process and the subprocess is exclusive, so the data between the sub-processes is independent, and the lock is not the same lock. It is necessary to pass the lock to the child process to ensure that each child process uses the same lock. t_l= [] forIinchRange (100): T= Thread (target=Task) T_l.append (t) t.start () forTinchT_l:t.join ()Print('Master', N)
Operation Result:
Main 0
View Code
The role of mutexes: To turn parallel into serial.
5.1.15 the mutex of a thread