2023年11月29日发(作者:)

python捕捉线程异常_解决pythonThreadPoolExecutor线程池

中的异。。。

问题

最近写了涉及线程池及线程的 python 脚本,运⾏过程中发现⼀个有趣的现象,线程池中的⼯作线程出现问题,引发了异常,但是主线程没

有捕获异常,还在发现 BUG 之前⼀度以为线程池代码正常返回。

先说重点

这⾥主要想介绍 python PoolExecutor 线程池中的 worker 引发异常的时候,并不会直接向上抛起异

常,⽽是需要主线程通过调⽤ion(timeout=None) ⽅法主动获取 worker 的异常。

thread: MainThread [INFO] Master starts thread worker

sleep(5)

("I am slave. I am working. I am going to sleep 3s")

INFO [thread: WorkExecutor_0] Master is going to sleep 5s

def main():