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.
- lock = Semaphore(2)
- def test():
- with lock:
- for i in range(5):
- print currentThread().name, i
- sleep(1)
- for i in range(5):
- Thread(target = test).start()
Output:
- $ ./main.py
Thread-1 0 <--- Thread-1 and Thread-2 get the lock
- Thread-2 0
- Thread-1 1
- Thread-2 1
- Thread-1 2
- Thread-2 2
- Thread-1 3
- Thread-2 3
- Thread-1 4
- Thread-2 4
Thread-3 0 <--- Thread-3 and Thread-4 get the lock
- Thread-4 0
- Thread-3 1
- Thread-4 1
- Thread-3 2
- Thread-4 2
- Thread-3 3
- Thread-4 3
- Thread-3 4
- Thread-4 4
Thread-5 0 <--- Thread-5 get the lock
- Thread-5 1
- Thread-5 2
- Thread-5 3
- Thread-5 4
The above is a detailed description of the actual application and operation solution of Semaphore In the Python Library.