One, what is the semaphore.
The semaphore is also a lock.
The primary use of semaphores is to control the concurrency of threads, Boundedsemaphore or semaphore manage a built-in counter, each time the acquire () method is called, the counter-1, each time the release () method is called, the internal counter +1.
However, it is important to note that the counter inside the semaphore cannot be less than 0! When the counter inside is equal to 0, the thread is locked into a blocking state until the other thread calls the release method.
The only difference between Boundedsemaphore and semaphore is that the former will check that the value of the counter exceeds the initial value of the counter when it calls release (), and throws an exception if it is exceeded.
Ii. examples of semaphore usage.
#!/usr/local/bin/python2.7
#-*-Coding:utf-8-*-
Import threading
Import time
Semaphore = Threading. Semaphore (5) #设置同一次只能最多有5个线程通过.
def func ():
If Semaphore.acquire ():
Print Threading.currentthread (). GetName () + "semaphore"
Time.sleep (2)
Semaphore.release ()
For _ in range (20):
T1 = Threading. Thread (Target=func)
T1.start ()
Output Run Result:
Thread-1semaphore
Thread-2semaphore
Thread-3semaphore
Thread-4semaphore
Thread-5semaphore
Thread-6semaphore
Thread-7semaphore
Thread-8semaphore
Thread-9semaphore
Thread-10semaphore
Thread-13semaphore
Thread-11semaphore
Thread-12semaphore
Thread-14semaphore
Thread-15semaphore
Thread-17semaphore
Thread-20semaphore
Thread-19semaphore
Thread-18semaphore
Thread-16semaphore
A maximum of 5 threads were released at a time, a bit like the concept of parking spaces.
Three, the difference between the signal volume and the recursive lock.
Personal Understanding ~ The difference between the semaphore and the recursive lock is not, in the semaphore, the same lock, multiple threads can operate the same shared data, the recursive lock before the lock is freed a thread can only manipulate one shared data.
This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1925456
11.python Concurrency Primer (part6 semaphore semaphore)