学习Python线程池

学习Python线程池

from concurrent.futures import ThreadPoolExecutor,as_completed
import time

def test1(num):
    lit1 = []
    for i in range(num):
        time.sleep(3)
        lit1.append(i)
    return lit1

def test2(num):
    lit1 = []
    for i in range(num):
        time.sleep(5)
        lit1.append(i)
    return lit1

def test3(num):
    lit1 = []
    for i in range(num):
        time.sleep(7)
        lit1.append(i)
    return lit1

start_time=time.time()
t = ThreadPoolExecutor(max_workers=5) # 创建一个最大容纳数量为5的线程池
task_list=[t.submit(test1, 1),t.submit(test2, 2),t.submit(test3, 3)]
# task_list=[]
# for i in range(5):
#     task_list.append(t.submit(test3, 3))
# task1 = t.submit(test1, 1)
# task2 = t.submit(test2, 2)  # 通过submit提交执行的函数到线程池中
# task3 = t.submit(test3, 3)

for future in as_completed(task_list):
    print(future.done()) # 通过done来判断线程是否完成
    print(future.result()) # 通过result来获取返回值

end_time=time.time()
print(end_time-start_time)

执行结果:
True
[0]
True
[0, 1]
True
[0, 1, 2]
21.00355625152588

参考: https://www.jianshu.com/p/6d6e4f745c27

你可能感兴趣的:(多线程)