【发布时间】:2011-10-29 20:39:42
【问题描述】:
我有一个程序使用 python 的包多处理和队列。我的一个函数有这样的结构:
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
但我得到了错误,就好像我没有发现异常一样。要捕获的正确异常是什么?
【问题讨论】:
标签: python queue multiprocessing