multiprocessing.Pool 捕獲error

調用 pool.apply_async 後沒有報錯直接退出,導致我一直以爲是 join 後主進程沒有阻塞,直接結束導致子進程直接退出。原來是子進程的執行時有error,但是沒有捕獲到

 

import multiprocessing as mp

class A:
    def __init__(self,re):
        self.re = re

def do_stuff(num):
    result = 5/(2 - num)  #Line 8
    return A(result) 

def success_handler(result:A):
    print("success",result.re)

def error_handler(e):
    print(e.__cause__)

if __name__ == '__main__':
    with mp.Pool(2) as my_pool:
        results =  [
            my_pool.apply_async(
                do_stuff, 
                args=(i,),
                callback=success_handler, 
                error_callback=error_handler
            ) 
            for i in range(3)
        ]

        try:
            for result_obj in results:
                print("result is: {}".format(result_obj.get()))
        except ZeroDivisionError as e:
            print("Oh, boy.  This is the second time I've seen this error.")

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章