from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def myfunc(ip):
print(f"{ip} start.")
time.sleep(1)
print(f"{ip} done.")
return f"{ip} done."
if __name__ == '__main__':
ip_list = [
f"10.99.8.{host}"
for host in range(1, 50)
]
# 方法一
with ThreadPoolExecutor() as pool:
# with ThreadPoolExecutor(max_workers=5) as executor: # 指定5个线程
results = pool.map(myfunc, ip_list)
# 输出返回值
for result in results:
print(result)
# 方法二
from concurrent import futures
with ThreadPoolExecutor() as pool:
futures = [pool.submit(myfunc, ip) for ip in ip_list]
# for ip in ip_list:
# future = pool.submit(myfunc, ip)
# futures.append(future)
# 输出返回值一 有序结果,按顺序显示结果
for future in futures:
print(future.result())
# 输出返回值二 无序结果,先完成先显示
for future in as_completed(futures):
print(future.result())
好用的线程池ThreadPoolExecutor
最新推荐文章于 2023-10-30 14:59:36 发布