0%

python | 线程池的不断堆积

请看下面的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import time
from concurrent.futures import ThreadPoolExecutor

pool = ThreadPoolExecutor(max_workers=5)


def t(i):
print(i)
if i == 5:
time.sleep(20)
time.sleep(1)

if __name__ == '__main__':
while 1:

tasks = []
for i in range(10000):
tasks.append(pool.submit(t, i))

time.sleep(0.1)
print("=============")

上面的代码非常不对。

在不断的 while 循环中,会不断的给 tasks 提交任务,旧的任务还没执行结束,新的任务已经提交。

解决的方法有下面几种方法

请我喝杯咖啡吧~