Detailed description of the Semaphore operation solution in Python Library

Source: Internet
Author: User

Python Library is a commonly used language in computer languages. Many people will be exposed to the Semaphore computer language in Python Library. The following article describes the actual application and operation solutions, I hope you will be able to read the following articles for your help.

Python Library Semaphore is the same as. NET Semaphore, which limits the number of threads that can simultaneously access a certain resource.

 
 
  1. lock = Semaphore(2)  
  2. def test():  
  3. with lock:  
  4. for i in range(5):  
  5. print currentThread().name, i  
  6. sleep(1)  
  7. for i in range(5):  
  8. Thread(target = test).start()   

Output:

 
 
  1. $ ./main.py 

Thread-1 0 <--- Thread-1 and Thread-2 get the lock
 

 
 
  1. Thread-2 0  
  2. Thread-1 1  
  3. Thread-2 1  
  4. Thread-1 2  
  5. Thread-2 2  
  6. Thread-1 3  
  7. Thread-2 3  
  8. Thread-1 4  
  9. Thread-2 4 

Thread-3 0 <--- Thread-3 and Thread-4 get the lock
 

 
 
  1. Thread-4 0  
  2. Thread-3 1  
  3. Thread-4 1  
  4. Thread-3 2  
  5. Thread-4 2  
  6. Thread-3 3  
  7. Thread-4 3  
  8. Thread-3 4  
  9. Thread-4 4 

Thread-5 0 <--- Thread-5 get the lock
 

 
 
  1. Thread-5 1  
  2. Thread-5 2  
  3. Thread-5 3  
  4. Thread-5 4 

The above is a detailed description of the actual application and operation solution of Semaphore In the Python Library.

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.