python__系统 : 线程池

参考文档: https://www.jianshu.com/p/b9b3d66aa0be

使用  ThreadPoolExecutor  类,  as_completed 是迭代器, 如果有任务执行完成有返回值, 则触发as_completed 的迭代.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from concurrent.futures import ThreadPoolExecutor, as_completed
import time


# 参数times用来模拟网络请求的时间
def get_html(times):
    time.sleep(times)
    print("第{}个任务完成".format(times))
    return times


executor = ThreadPoolExecutor(max_workers=3)
urls = [3, 2, 4]  # 并不是真的url
all_task = [executor.submit(get_html, url) for url in urls]

for future in as_completed(all_task):
    data = future.result()
    print("返回第 {} 个任务的结果".format(data))

 


posted @ 2019-09-17 16:19  cccy0  阅读(170)  评论(0编辑  收藏  举报