Python Multiprocess Pool. How to exit the script when one of the worker process determines no more work needs to be done?

女生的网名这么多〃 提交于 2019-11-27 02:02:40

You can use callbacks from Pool.apply_async.

Something like this should do the job for you.

from multiprocessing import Pool


def part_crack_helper(args):
    solution = do_job(args)
    if solution:
        return True
    else:
        return False


class Worker():
    def __init__(self, workers, initializer, initargs):
        self.pool = Pool(processes=workers, initializer=initializer, initargs=initargs)

    def callback(self, result):
        if result:
            print "Solution found! Yay!"
            self.pool.terminate()

    def do_job(self):
        for args in product(seed_str, repeat=4):
            self.pool.apply_async(part_crack_helper, args=args, callback=self.callback)
        self.pool.close()
        self.pool.join()
        print "good bye"


w = Worker(num_proc, init, [total_count])
w.do_job()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!