The examples in this article describe Python multithreading threading. Lock lock usage examples, share to everyone for your reference. The specific analysis is as follows:
Python's locks can be extracted independently.
Copy the Code code as follows:
Mutex = Threading. Lock ()
#锁的使用
#创建锁
Mutex = Threading. Lock ()
#锁定
Mutex.acquire ([timeout])
#释放
Mutex.release ()
Locking method acquire can have an optional parameter of timeout time. 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.
Copy the Code code as follows:
#!/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
Hopefully this article will help you with Python programming.