完整代码:
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, wait, ALL_COMPLETED
def test(num):
sum = 0
for i in range(num):
sum += i
return sum
def main():
pool = ProcessPoolExecutor(max_workers=8)
task = [pool.submit(test, num) for num in [3, 5, 7]]
wait(task, return_when=ALL_COMPLETED)
for i in task:
print(i.result())
if __name__ == '__main__':
main()
简单介绍每一步:
一、导入包
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, wait, ALL_COMPLETED
二、创建一个函数
这个函数是打算要做的事。
def test(num):
sum = 0
for i in range(num):
sum += i
return sum
三、创建一个主函数,在主函数里面创建进程池(或线程池)
def main():
pool = ProcessPoolExecutor(max_workers=3) # 进程池
# pool = ThreadPoolExecutor(max_workers=3) # 线程池
创建进程池时max_workers的最大值为CPU核心的两倍;创建线程池时max_workers的最大值为CPU核心的五倍。
四、将任务放入进/线程池中
task = [pool.submit(test, num) for num in [3, 5, 7]] # 注意test后面没有括号!!!
五、等待进/线程池完成任务
wait(task, return_when=ALL_COMPLETED)
这里是等待所有任务完成才能拿到结果。也可以不用等待所有任务完成就拿到结果,即每个进/线程执行完就可以拿到结果,去掉return_when就行。
六、得到结果
for i in task:
print(i.result())