- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我知道 threading.Lock()
等于 threading.Semaphore(1)
。
threading.Lock()
是否也等于 threading.BoundedSemaphore(1)
?
最近我看到了threading.BoundedSemaphore()
,它们有什么区别?例如在以下代码片段中(对线程应用限制):
import threading
sem = threading.Semaphore(5)
sem = threading.BoundedSemaphore(5)
最佳答案
Semaphore
可以被释放的次数多于它被获取的次数,这将使它的计数器增加到起始值以上。 有界信号量
can't高于起始值。
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.')
关于python - .Semaphore() 和 .BoundedSemaphore() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48971121/
有谁知道这两种锁定结构中哪一种更快?我有: private static final Object mutex = new Object(); void method() { synchron
如果在尝试获取信号量时引发 KeyboardInterrupt,则也尝试释放相同信号量对象的线程将无限期挂起。 代码: import threading import time def worker(
我知道 threading.Lock() 等于 threading.Semaphore(1)。 threading.Lock() 是否也等于 threading.BoundedSemaphore(1)
multiprocessing.BoundedSemaphore(3) 与 multiprocessing.Sempahore(3) 有何不同? 我希望 multiprocessing.Bounded
我使用 manage.py 命令创建大约 200 个线程来检查远程主机。我的数据库设置允许我使用 120 个连接,所以我需要使用某种池。我试过使用单独的线程,像这样 class Pool(Thread
我是一名优秀的程序员,十分优秀!