python进程池一个进程卡住_Python多进程池。当工作进程之一确定不需要执行更多工作时,如何退出脚本?...

mp.set_start_method('spawn')

total_count = Counter(0)

pool = mp.Pool(initializer=init, initargs=(total_count,), processes=num_proc)

pool.map(part_crack_helper, product(seed_str, repeat=4))

pool.close()

pool.join()

So I have a pool of worker process that does some work. It just needs to find one solution. Therefore, when one of the worker processes finds the solution, I want to stop everything.

One way I thought of was just calling sys.exit(). However, that doesn't seem like it's working properly since other processes are running.

One other way was to check for the return value of each process calls (the return value of part_crack_helper function) and call terminate on that process. However, I don't know how to do that when using that map function.

How should I achieve this?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值