Concept python for multi-thread lock

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.