我知道threading.Lock()
等于threading.Semaphore(1)
.
Is also threading.Lock()
等于threading.BoundedSemaphore(1)
?
我最近看到threading.BoundedSemaphore()
,它们之间有什么区别?例如,在以下代码片段中(对线程应用限制):
import threading
sem = threading.Semaphore(5)
sem = threading.BoundedSemaphore(5)
A Semaphore
释放的次数可以多于获取的次数,这将使其计数器高于起始值。 ABoundedSemaphore
can't https://docs.python.org/3.6/library/threading.html#threading.BoundedSemaphore高于起始值。
from threading import Semaphore, BoundedSemaphore
# Usually, you create a Semaphore that will allow a certain number of threads
# into a section of code. This one starts at 5.
s1 = Semaphore(5)
# When you want to enter the section of code, you acquire it first.
# That lowers it to 4. (Four more threads could enter this section.)
s1.acquire()
# Then you do whatever sensitive thing needed to be restricted to five threads.
# When you're finished, you release the semaphore, and it goes back to 5.
s1.release()
# That's all fine, but you can also release it without acquiring it first.
s1.release()
# The counter is now 6! That might make sense in some situations, but not in most.
print(s1._value) # => 6
# If that doesn't make sense in your situation, use a BoundedSemaphore.
s2 = BoundedSemaphore(5) # Start at 5.
s2.acquire() # Lower to 4.
s2.release() # Go back to 5.
try:
s2.release() # Try to raise to 6, above starting value.
except ValueError:
print('As expected, it complained.')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)