我有一个python进程池,如果在我想要退出池执行的任何一个进程中发生异常的话。
我已经加入了池中的所有进程,所以join等待每个进程完成。如果在目标函数中提出sys.exit(1),系统将进行无限等待,因为连接仍在等待进程完成。
如何在代码中使用联接时退出执行?
from multiprocessing import Pool
import time
import sys
def printer(ip):
try:
for _ in xrange(5):
print ip+str(_)
time.sleep(1.0)
except Exception as e:
print e
sys.exit(2)
def test():
pool = Pool(processes=2)
for i in ["hello",5]:
result = pool.apply_async(printer,(i,))
pool.close()
pool.join()
print "good bye"
test()发布于 2015-01-11 20:50:15
只需返回到父进程操作的状态,并使用回调来对失败作出反应。
import time
from multiprocessing import Pool
def printer(ip):
try:
for _ in xrange(5):
print ip+str(_)
time.sleep(1.0)
return True
except Exception as e:
print e
return False
class Worker():
def __init__(self):
self.pool = Pool(processes=2)
def callback(self, result):
if not result:
print "Error raised in child process. Terminating.."
self.pool.terminate()
def do_job(self):
for i in ["hello", 5]:
self.pool.apply_async(printer, (i,), callback=self.callback)
self.pool.close()
self.pool.join()
print "good bye"
def test():
w = Worker()
w.do_job()https://stackoverflow.com/questions/26832175
复制相似问题