赞
踩
-
- import asyncio
- import time
- import requests
- from concurrent.futures import ALL_COMPLETED,FIRST_COMPLETED,FIRST_EXCEPTION
-
- async def task2():
- print('task2')
- # res = requests.get('https://www.baidu.com',verify=False)
- # print(res.status_code)
- await asyncio.sleep(3)
- # print('sleep 3 task2')
- return 111
- async def task(num):
- print('task')
- t = loop.create_task(task2())
- await asyncio.sleep(num)
- await t
- print('sleep 2 task')
- if num == 2:
- raise NotImplemented
-
- return f'task res {num}'
-
- async def main(loop):
- # 正确的写法1
- task1 = [loop.create_task(task(1)) for _ in range(1100)] # 3.7 可用 asysico.create_task()
- task22 = loop.create_task(task2())
- for t in task1:
- await t
- await task22
- # 写法2
- # res1 = asyncio.gather(task(1))
- # res2 = asyncio.gather(task(1))
- # res3 = asyncio.wait([task(1),task(3)],return_when=FIRST_COMPLETED)
- # res3 = asyncio.wait([task(1) for i in range(100)],return_when=ALL_COMPLETED) # wait方式如果不一次写全 会导致异步失败
- # res4 = asyncio.wait([task(1) for i in range(100)],return_when=ALL_COMPLETED)
- # # await res1
- # # await res2
- # pending,done = await res3
- # print(pending,done,"*"*11)
- # res = await asyncio.gather(task(1))
- # res = await asyncio.gather(task(1))
- # print(res)
- # t1 = [asyncio.ensure_future(task(5)) for _ in range(20) ]
- # t2 = asyncio.ensure_future(task2())
- # for t in t1:
- # res = await t
- # print(f'res = {res}')
- # await t2
-
-
- # 错误的写法1 假异步
- # await loop.create_task(task())
- # await loop.create_task(task2())
- # 错误的写法2 假异步
- # await asyncio.ensure_future(task2())
- # await asyncio.ensure_future(task2())
-
-
-
- if __name__ == '__main__':
- # 创建任务的方法
- # 1. asyncio.gather 全称黑盒 只告诉结果
- # 2. asyncio.wait 状态+结果 有参数 选择返回的时机 done,pending = awit res
- # 3. loop.create_task
- # 4. asyncio.ensure_future 无返回值
- # 5. asyncio.create_task # 3.7
- # 6. asyncio.shield # 确保任务完成 即使cancel 也会被执行得到结果
-
- start = time.perf_counter()
- loop = asyncio.get_event_loop()
- # method 1
- # tasks =asyncio.gather(*[task(_) for _ in range(1000)],return_exceptions=True) # 方式一 gather
- # loop.run_until_complete(tasks)
- # print(tasks.result())
- # # end 1
-
- # method 2
-
- # tasks = loop.create_task(task())
- # loop.run_until_complete(tasks)
-
- # method 3 asyncio.wait
- tasks = asyncio.wait([task2() for _ in range(1000)])
- done,pending = loop.run_until_complete(tasks)
- print(done)
-
- # method 4 main 中 创建
- # loop.run_until_complete(loop.create_task(main(loop)))
- # loop.run_forever()
- loop.time()
- print(f'耗时{time.perf_counter()-start}s')
'运行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。