ThreadPoolExecutor获取线程池中已经运行完的任务结果

方法一: 使用as_completed函数

复制代码
from concurrent.futures import ThreadPoolExecutor, as_completed
from time import sleep


def method(times):
    sleep(times)
    print('sleep {} secondes'.format(times))
    return times


pool = ThreadPoolExecutor(max_workers=2)
seconds = [i for i in range(10)]
tasks = [pool.submit(method, (second)) for second in seconds]
# as_completed函数会将运行完的任务一个一个yield出来
# 它返回任务的结果与提交任务的顺序无关,谁先执行完返回谁
for future in as_completed(tasks):
    print(future.result())
复制代码

方法二: 使用map方法

复制代码
from concurrent.futures import ThreadPoolExecutor
from time import sleep


def method(times):
    sleep(times)
    print('sleep {} secondes'.format(times))
    return times


pool = ThreadPoolExecutor(max_workers=2)
seconds = [i for i in range(4)]
# map方法会将任务运行的结果yield出来
# map方法返回任务结果的顺序与提交任务的顺序一致
for data in pool.map(method, seconds):
    print(data)
复制代码

3.wait方法

wait方法用于阻塞主线程的运行, 可以设置当某些子线程运行完成以后再继续执行主线程
其第一个参数是future对象或future对象列表,return_when参数用于指定当哪些任务运行完成时继续执行主线程,其参数有:
FIRST_COMPLETED = 'FIRST_COMPLETED'
FIRST_EXCEPTION = 'FIRST_EXCEPTION'
ALL_COMPLETED = 'ALL_COMPLETED'
复制代码
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED, FIRST_COMPLETED
import time
 
# 参数times用来模拟网络请求的时间
def get_html(times):
    time.sleep(times)
    print("get page {}s finished".format(times))
    return times
 
executor = ThreadPoolExecutor(max_workers=2)
urls = [3, 2, 4] # 并不是真的url
all_task = [executor.submit(get_html, (url)) for url in urls]
wait(all_task, return_when=ALL_COMPLETED)
print("main")

复制代码

 




posted on   帅胡  阅读(1052)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 三行代码完成国际化适配,妙~啊~
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
历史上的今天:
2015-05-14 获取ping的最短、最长、平均时间

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示