Python multithreaded threading.Lock usage example

  • 2020-04-02 14:20:24
  • OfStack

This article provides an example of how to use a python multithreaded threading.Lock Lock. Specific analysis is as follows:

Python's locks can be extracted independently

mutex = threading.Lock()
# The use of the lock
# Create a lock
mutex = threading.Lock()
# lock
mutex.acquire([timeout])
# The release of
mutex.release()

The lock method acquire can have an optional timeout for the timeout time. If timeout is set, the lock can be determined by the return value after the timeout, so that some other processing can be done.

#!/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

I hope this article has helped you with your Python programming.


Related articles: