Concept python for multi-thread lock
Several people asked me how to lock the resources, in fact, not to lock resources, but to lock the resources, you can define multiple locks, like the following code, when you need to monopolize a resource, any lock can lock the resource
It's like you can lock the same one with different locks.
#coding: Utf-8import Threading Import Time counter = 0counter_lock = Threading. Lock () #只是定义一个锁, not to lock the resources, you can define multiple locks, like the next 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 () #可以使用上边三个锁的任何一个来锁定资源 class MyThread (threading. Thread): #使用类定义thread, inherit threading. Thread def __init__ (self,name): Threading. Thread.__init__ (self) self.name = "thread-" + str (name) def run (self): #run函数必须实现 global Counter,co Unter_lock #多线程是共享资源的, use global variable time.sleep (1); If Counter_lock.acquire (): #当需要独占counter资源时, must be locked first, this lock can be any one lock, can use the above definition of any one of the 3 locks counter + = 1 PR int "I am%s, set counter:%s"% (self.name,counter) counter_lock.release () #使用完counter资源必须要将这个锁打开 for other threads to use if __name__ = = "__main__": For I in Xrange (1,101): My_thread = MyThread (i) My_thread.start ()
Concept of lock in multi-thread Python