concurrent.futures
# _*_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 超时时间 #