我有一个程序使用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
但我得到了错误,好像我没有抓到异常。要捕获的正确异常是什么?