简体   繁体   English

如何停止 multiprocessing.Pool.map 异常

[英]How to stop multiprocessing.Pool.map on exception

When I raise an exception inside my thread_function , it doesn't stop the rest of the map processing.当我在thread_function内部引发异常时,它不会停止map处理的 rest 。 I'd like to stop it.我想阻止它。

def thread_function(n):
    if n == 10:
        raise Exception('Stop everything!')

pool = Pool(processes = 4)
pool.map(thread_function, range(1, 1000), chunksize = 1)

I'd expect no more processing after one thread reached n == 10 .我希望在一个线程达到n == 10后不再进行处理。

I don't know of a way to do this directly with map but you can monitor an async_map like this...我不知道用map直接执行此操作的方法,但是您可以像这样监视async_map ...

from multiprocessing import Pool
import time

def thread_function(n):
    if n == 10:
        print('Raising Exception')
        raise Exception('Stop everything!')
    print(n)
    time.sleep(0.1)

pool = Pool(processes = 4)
result = pool.map_async(thread_function, range(1, 1000), chunksize = 1)
while not result.ready():
    if not result._success:
        print('Exiting for failure')
        pool.terminate()
        pool.join()
        break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM