码迷,mamicode.com
首页 > 其他好文 > 详细

concurrent.futures

时间:2018-01-07 23:30:56      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:auth   任务   exe   一个   can   阻塞   判断   超时   方式   

# _*_coding:utf-8_*_
# author:leo
# date:
# email:alplf123@163.com
from concurrent.futures import *
from urllib import request
import time
import random

tasks = []
def test(val):
    rand = random.randint(1, 10)
    print(‘任务开始 delay: ‘, rand)
    time.sleep(rand) # 模拟耗时
    return ‘result: ‘ + str(val)

# 初始化线程池
pool = ThreadPoolExecutor(max_workers=5)
tasks = [pool.submit(test, x) for x in range(1, 10)]
#print(t.cancel()) # 尝试取消一个任务 成功True 失败Flase
# try:
#     for t in as_completed(tasks, 10):
#         print(t, ‘status: ‘, t.done(), ‘result: ‘, t.result())
# except TimeoutError as e:
#         print(‘can`t finish in time‘)
#
wait(tasks) #阻塞任务全部完成
for t in tasks:  #查看所有任务状态
    print(t.done())
# for t in tasks:
#     print(t.running()) # 判断任务状态
#
# #wait() #传入可迭代对象,阻塞所有任务
# for t in tasks:
#     print(t.done()) # 任务是否完成
# for t in tasks:
#     print(t.result()) #阻塞的方式获取任务的结果 可以设置timeout 超时时间
#

  

concurrent.futures

标签:auth   任务   exe   一个   can   阻塞   判断   超时   方式   

原文地址:https://www.cnblogs.com/alplf123/p/8232501.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!