Multi-thread lock concept python

Source: Internet
Author: User

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 ()


 

 

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.