gpt4 book ai didi

python - 使用单线程时 Queue.full() 是否可靠?

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:38 28 4
gpt4 key购买 nike

Python 的 thread-safe Queue object 有一个有用的函数,名为 Queue.full()使用以下文档:

Return True if the queue is full, False otherwise. If full() returns True it doesn’t guarantee that a subsequent call to get() will not block. Similarly, if full() returns False it doesn’t guarantee that a subsequent call to put() will not block.

很明显,在多线程场景下,多线程 put() 队列中的项目和多线程 get() 项目,存在竞争条件。但是,如果只有一个线程使用 put(),而一个不同的线程使用 get() 则无法获取 full() 的值可信吗?
这是一个特定于 Python 实现的问题吗?如果是这样,CPython 的答案是什么?

最佳答案

如果您的意思是您只使用一个线程来做所有事情,那么是的。如果没有其他东西正在访问它,那么它就无法更改。

如果您的意思是总体上有两个线程,那么不会,仍然存在竞争条件的机会。

无论哪种方式,真正的问题是您为什么要这样做?尝试一下,如果失败则捕获异常 - 这就是 Python 方式。

try:
some_queue.get_nowait()
except queue.Empty:
do_something_else()

这样做的好处是在未来是线程安全的,并且在任何情况下都避免了竞争条件(不需要线程来引起它,你可以只调用改变检查和获取之间的代码偶然)。

编辑:作为larsmans在下面的评论中指出,在与竞争条件有关的其他问题中,CPython 有 Queue.full() 标记为 likely to be removed at some point,所以有是避免它的另一个原因。

关于python - 使用单线程时 Queue.full() 是否可靠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10801019/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com