0
考慮下面的程序結構我正在尋找一種方式來:的Python多的異常處理
檢測孩子失敗在父進程
終止所有進程(父母和子女)並在退出狀態碼1
做到以上而不放鬆最大隊列大小
下面的代碼:
import multiprocessing
def worker1(queue1, queue2):
while True:
item = queue1.get()
if item == 10:
raise
if item == 'stop':
return
# do something with item that generates multiple queue entries
for x in xrange(1000):
queue2.put(x)
def worker2(queue2, queue3):
while True:
item = queue2.get()
if item == 'stop':
return
# do something with item, only one result to pass to the next queue
queue3.put(1)
def worker3(queue3):
while True:
item = queue3.get()
if item == 'stop':
return
# do something with item
def main():
queue1 = multiprocessing.Queue()
queue2 = multiprocessing.Queue(100)
queue3 = multiprocessing.Queue(100)
pool1 = multiprocessing.Pool(2, worker1, (queue1,queue2,))
pool2 = multiprocessing.Pool(8, worker2, (queue2,queue3,))
pool3 = multiprocessing.Pool(4, worker3, (queue3,))
for i in xrange(100):
queue1.put(i)
for _ in range(pool1.__dict__['_processes']):
queue1.put('stop')
pool1.close()
pool1.join()
for _ in range(pool2.__dict__['_processes']):
queue2.put('stop')
pool2.close()
pool2.join()
for _ in range(pool3.__dict__['_processes']):
queue3.put('stop')
pool3.close()
pool3.join()
print 'finished'
if __name__ == '__main__':
main()
謝謝!
代碼的工作原理?如果是,請轉至CodeReview。如果沒有,請向我們解釋問題。 – Mikael
該代碼有效,但父進程不知道子進程中未捕獲到的異常。我正在尋找一些幫助來檢測它們,並在發生未捕獲的異常時關閉所有進程(父進程和子進程)。 – Vlassios
那麼,通常的方法來捕捉異常是使用'try:... except:raise〜exception type〜' – Mikael