gpt4 book ai didi

python - 在 python 的多处理中检查空队列

转载 作者:太空狗 更新时间:2023-10-29 21:25:03 24 4
gpt4 key购买 nike

我有一个程序使用 python 的包 multiprocessing 和 Queue。我的一个函数具有以下结构:

from multiprocessing import Process, Queue
def foo(queue):
while True:
try:
a = queue.get(block = False)
doAndPrintStuff(a)
except:
print "the end"
break

if __name__ == "__main__"
nthreads = 4
queue = Queue.Queue()
# put stuff in the queue here
for stuff in moreStuff:
queue.put(stuff)
procs = [Process(target = foo, args = (queue,)) for i in xrange(nthreads)]
for p in procs:
p.start()
for p in procs:
p.join()

想法是,当我尝试从队列中提取数据并且队列为空时,它会引发异常并终止循环。所以我有两个问题:

1) 这是一个安全的习语吗?有没有更好的方法来做到这一点?

2) 我试图找到当我尝试从空队列中 .get() 时引发的确切异常是什么。目前我的程序正在捕获所有异常,当错误出现在其他地方并且我只收到“结束”消息时,这很糟糕。

我试过:

  import Queue
queue = Queue.Queue()
[queue.put(x) for x in xrange(10)]
try:
print queue.get(block = False)
except Queue.Empty:
print "end"
break

但是我得到了错误,就好像我没有捕获到异常一样。要捕获的正确异常是什么?

最佳答案

异常应该是 Queue.Empty。但是你确定你遇到了相同错误吗?在您的第二个示例中,您还将队列本身从 multiprocessing.Queue 切换为 Queue.Queue,我认为这可能是问题所在。

这可能看起来很奇怪,但你必须使用 multiprocessing.Queue 类,但使用 Queue.Empty 异常(你必须自己从 队列模块)

关于python - 在 python 的多处理中检查空队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7109093/

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