问题描述
在python线程池中的线程,如果在运行过程中如果遇到异常,是卡死然后线程池中的线程减少一,还是卡死后,线程池中的再填充一个新的线程.又或者是其他情况?
代码验证
代码如下:
from concurrent.futures import ThreadPoolExecutor
import threading
import time
pool = ThreadPoolExecutor(2)#创建线程池,设置可用的线程个数
def one(arg):
ret = threading.current_thread()
print('one %s : %s' % (arg, ret)) #输出当前线程
v=[]
v[1] #制造错误
def two(arg):
time.sleep(2)
ret = threading.current_thread() #输出当前线程
print('two %s : %s' % (arg, ret))
for i in range(1,11):
pool.submit(one,i) #从线程池中申请一个线程执行函数one,
#如果线程池中有空闲的线程,则申请成功,如果没有,就等待线程完成任务后申请执行
for i in range(1,11):
pool.submit(two,i,)#pool.submit(函数,参数),源码:def submit(self, fn, *args, **kwargs):
运行结果:
one 1 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
one 2 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
one 3 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
one 4 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
one 5 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
one 6 : <Thread(ThreadPoolExecutor-0_1, started daemon 11628)>
one 7 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
one 8 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
one 9 : <Thread(ThreadPoolExecutor-0_1, started daemon 11628)>
one 10 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
two 2 : <Thread(ThreadPoolExecutor-0_1, started daemon 11628)>
two 1 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
two 3 : <Thread(ThreadPoolExecutor-0_1, started daemon 11628)>
two 4 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
two 5 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
two 6 : <Thread(ThreadPoolExecutor-0_1, started daemon 11628)>
two 7 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
two 8 : <Thread(ThreadPoolExecutor-0_1, started daemon 11628)>
two 10 : <Thread(ThreadPoolExecutor-0_0, started daemon 8580)>
two 9 : <Thread(ThreadPoolExecutor-0_1, started daemon 11628)>
进程已结束,退出代码0
结论
由代码验证可以看出,线程池中的线程遇到异常会直接退出,但是该线程并不会‘死亡’,会直接进行下一个任务,并且不会抛出异常