【问题标题】:How to exit all the joined processes in case any one has an exception - Python如果任何一个出现异常,如何退出所有加入的进程 - Python
【发布时间】:2014-11-09 19:13:55
【问题描述】:

我有一个python进程池,如果任何一个进程发生异常我想退出池的执行

我已加入池中的所有进程,因此加入等待每个进程完成。 如果我在目标函数中提出 sys.exit(1) ,系统会无限等待,因为连接仍在等待进程完成。

在代码中使用join时如何退出执行

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()

【问题讨论】:

    标签: python python-multiprocessing


    【解决方案1】:

    只需将操作的状态返回给父进程,并使用回调对失败做出反应。

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多