Multi-thread lock concept python
Multi-thread lock concept python
Several people asked me how to lock resources. Instead of locking resources, I used locks to lock resources. You can define multiple locks, like the following code, when you need to exclusively occupy a resource, any lock can lock the resource.
Just like you can lock the same lock with different locks.
# Coding: utf-8import threading import time counter = 0counter_lock = threading. lock () # define a Lock instead of locking resources. You can define multiple locks, such as the following two lines of code. When you need to occupy this resource, any lock can lock this resource counter_lock2 = threading. lock () counter_lock3 = threading. lock () # You can use any of the above three locks to Lock the resource class MyThread (threading. thread): # use a class to define thread and inherit from threading. thread def _ init _ (self, name): threading. thread. _ init _ (self) self. name = "Thread-" + str (name) def run (self): # The run function must implement global counter. counter_lock # multiple threads share resources and use the global variable time. sleep (1); if counter_lock.acquire (): # When the counter resource needs to be exclusive, the lock must be locked first. This lock can be any one, any counter + = 1 print "I am % s, set counter: % s" % (self. name, counter) counter_lock.release () # after using the counter resource, you must open the lock so that other threads can use if _ name _ = "_ main __": for I in xrange (1,101): my_thread = MyThread (I) my_thread.start ()