Home > Article > Backend Development > Introduction to semaphores and bounded semaphores under Python threads
This article brings you an introduction to semaphores and bounded semaphores under Python threads. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The semaphore is a counter-based synchronization primitive. Each time the acquire() method is called, the counter is decremented by 1, and each time release() is called ) method, this counter is incremented by 1. If the counter is 0, the acquire() method will block until another thread calls the release() method.
s=Semqphore(value)
Create a new semaphore. value is the initial value of the counter. If value is omitted, it will default to 1
s.acquire(blocking): Get the semaphore. If the internal counter is greater than 0, this method will decrement its value by 1.
Then return immediately. If its value is 0, this method blocks until another thread calls the release() method.
The behavior of the blocking parameter is the same as described for Lock and RLock objects.
s.release(): Release a semaphore by adding 1 to the internal counter value.
If the counter is 0 and another thread is waiting, the thread will be awakened.
If multiple threads are waiting, only one can be returned from its acquire() call, and the order is undefined.
bs=BoundedSemaphore(value)
Create a new bounded semaphore. value is the initial value of the counter. If omitted, it will default to 1.
BoundedSemaphore works exactly the same as Semaphore, but release() The number of operations cannot exceed the number of acquire() operations.
Semaphores can be used to send signals. For example, the acquire() and release() methods can be called from different threads to communicate between the producer and consumer threads.
Related recommendations:
Detailed explanation of the use of semaphores in Python3.X threads
python Semaphore (Semaphore) What is it? (detailed examples)
The above is the detailed content of Introduction to semaphores and bounded semaphores under Python threads. For more information, please follow other related articles on the PHP Chinese website!