.Semaphore()和.BoundedSemaphore()有什么区别? [英] What is the difference between .Semaphore() and .BoundedSemaphore()?

查看:429
本文介绍了.Semaphore()和.BoundedSemaphore()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

threading.Lock()等于threading.BoundedSemaphore(1)吗?

最近我遇到了threading.BoundedSemaphore(),两者之间有什么区别?例如以下代码段(对线程进行限制):

And newly I met threading.BoundedSemaphore(), what is the difference between these? such as the following code snippet (to apply limitation on threads):

import threading

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

推荐答案

Semaphore的释放次数可以超过获得的释放次数,这会使计数器的计数高于起始值. BoundedSemaphore 不能提高到起始值以上

A Semaphore can be released more times than it's acquired, and that will raise its counter above the starting value. A BoundedSemaphore can't be raised above the starting value.

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.')    

这篇关于.Semaphore()和.BoundedSemaphore()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆