gpt4 book ai didi

python - 清除 `deque` s : is it thread-safe?

转载 作者:太空宇宙 更新时间:2023-11-03 11:17:32 24 4
gpt4 key购买 nike

我一直在阅读有关 CPython 的 collections.deque 的线程安全性的文章 herehere .我知道 .append().popleft() 操作在线程间相互配合得很好,.appendleft().pop().

我的问题是:.popleft().clear() 之间是否同样适用?或者在 .popleft().pop() 之间失败?我的情况是我有一个消费者线程,称它为 A,不断 .popleft()ing 来自 deque d 的项目,以及一个生产者.append() 将它们放在右边的线程 B。在某些时候,我希望线程 B 能够说“取消所有未决项目”。如果我用

d.clear()

它是否会因为与线程 A 的 .popleft() 操作发生冲突而潜在地导致未定义的行为?如果我说:

while d:
try: d.pop()
except: break

代替?

最佳答案

来自documentation of the api :

Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction (emphasis mine)

这意味着您可以在任何一侧弹出并仍然享受好处。至于 clear() 方法,只能通过查看实现来确定,但我认为它的实现方式与您建议的方式相同。

编辑:此外,如果我从阻塞队列的 java 实现中没记错的话,对于所有预期目的,它应该非常接近这个,在队列对象上调用 clear() 不保证 当你在下一行代码中访问它时,你会发现它是空的

关于python - 清除 `deque` s : is it thread-safe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49114725/

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