import time
from comcurrent.futures import ThreadPoolExecutor,ProcessPoolExccoutor#这个方法可以用进程池或者线程池
def f1(i):
print(i)
time.sleep(2)
if __name__ == '__main__':
tp = ThreadPoolExecutor(4)#指定线程池的大小 #如果改成进程池则是ProcessPoolExecutor
lst = []
for i in range(10):
res = rp.submit(f1,i)#sunmit 翻译:异步 作用是给多线程或进程异步提交任务
lst.append(res)
tp.shutdown()主线程等待所有提交给线程池的任务,全部执行完毕 close+join
for i in lst:
print(i.result())#拿到结果 request 翻译: 结果
print('主程序运行结束')
本文介绍如何使用Python的ThreadPoolExecutor和ProcessPoolExecutor来创建线程池和进程池,实现任务的异步提交和执行。通过具体示例,展示了如何设置线程池或进程池的大小,提交任务并获取执行结果。
742

被折叠的 条评论
为什么被折叠?



