首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >.Semaphore()和.BoundedSemaphore()有什么区别?

.Semaphore()和.BoundedSemaphore()有什么区别?
EN

Stack Overflow用户
提问于 2018-02-25 15:08:18
回答 1查看 9.4K关注 0票数 17

我知道threading.Lock()等同于threading.Semaphore(1)

threading.Lock()是否也等同于threading.BoundedSemaphore(1)

最近我遇到了threading.BoundedSemaphore(),它们之间有什么不同?例如下面的代码片段(对线程应用限制):

代码语言:javascript
复制
import threading

sem = threading.Semaphore(5)
sem = threading.BoundedSemaphore(5)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-25 15:12:39

一个Semaphore被释放的次数可以比它获得的次数多,这会使它的计数器超过起始值。BoundedSemaphore can't将提升到起始值以上。

代码语言:javascript
复制
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.')    
票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48971121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档