Python locks can be extracted independently.
The code is as follows |
Copy Code |
Mutex = Threading. Lock () Use of Locks #创建锁 Mutex = Threading. Lock () #锁定 Mutex.acquire ([timeout]) #释放 Mutex.release () |
The locking method acquire can have an optional parameter timeout for a time-out period. If timeout is set, the return value can be used to determine if a lock has been obtained, allowing some other processing to be done.
The code is as follows |
Copy Code |
#!/usr/bin/env python #coding =utf-8 Import threading Import time
Class Mythread (threading. Thread): def run (self): Global num Time.sleep (1)
If Mutex.acquire (1): num = num+1 msg = self.name+ ' Set num to ' +str (num) Print msg Mutex.release () num = 0 Mutex = Threading. Lock () def test (): For I in range (5): t = Mythread () T.start () if __name__ = = ' __main__ ': Test () Thread-1 Set num to 1 Thread-3 Set num to 2 Thread-4 Set num to 3 Thread-5 Set num to 4 Thread-2 Set num to 5 |