With examples, it's a good idea.
is to not allow shared variables to be executed by individual threads, resulting in unexpected results
The lock class is defined in the threading module, allowing for easy handling of locks:
# Create a lock
Mutex = Threading. Lock ()
# Lock
Mutex.acquire ([timeout])
# Free
Mutex.release ()
Where the lock method acquire can have a time-out optional parameter of timeout. If timeout is set, the return value after timeout can be used to determine if a lock has been obtained, allowing for some additional processing.
#!/usr/bin/env python#-*-coding:utf-8-*-ImportThreadingImport TimeclassMyThread (Threading. Thread):defRun (self):GlobalNum Time.sleep (1) ifMutex.acquire (1): Num+ = 1msg= Self.name +'Set num to'+str (num)Printmsg mutex.release () num=0mutex=Threading. Lock ()defTest (): forIinchRange (5): T=MyThread () T.start () T.join ( )Print ' All done'if __name__=='__main__': Test ()
Python threading Knowledge re-learning c---thread mutex