問題描述
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.
我想到的一種方法就是調用 sys.exit().但是,這似乎無法正常工作,因為其他進程正在運行.
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.
另一種方法是檢查每個進程調用的返回值(part_crack_helper 函數的返回值)并在該進程上調用終止.但是,我不知道在使用該地圖功能時該怎么做.
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?
推薦答案
您可以使用來自 Pool.apply_async
的回調.
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()
這篇關于Python 多進程池.當其中一個工作進程確定不再需要完成工作時,如何退出腳本?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!