进程池在进程 发生错误/正常结束时,回调
python
import multiprocessing, time
from functools import partial
def worker(i):
print(f"Worker process {i} started")
if i == 5:
raise Exception(f'{i} error occured(自定义异常)')
time.sleep(5) # 模拟一些工作
def call_back_with_args(unknown_args, p):
print('call_back p:', p, unknown_args)
def error_callback(e):
print('error_callback : ', type(e), e)
if __name__ == '__main__':
with multiprocessing.Pool(processes=6) as pool:
for i in range(6):
pool.apply_async(worker, args=(i,),
callback=partial(call_back_with_args, p=i),
error_callback=error_callback)
pool.close() # 关闭进程池,不再接受新的任务
# time.sleep(2)
# pool.terminate() # 停止进程池中的所有工作进程,但不等待它们完成
pool.join()