import asyncio
import time
====================================
1.定义协程对象
async def hello(x):
# time.sleep(x) # time.sleep是一个同步操作语句,无法达到异步的结果
print('-222-', x)
await asyncio.sleep(x)
return '等待了{}秒'.format(x)
# return x
if name == 'main':
s_time = time.time()
# 2.创建协程对象
coro1 = hello(1)
coro2 = hello(2)
coro3 = hello(3)
# # 3.获取事件循环对象容器
loop = asyncio.get_event_loop()
# 4.将协程对象转化为task
tasks = [asyncio.ensure_future(coro1),
asyncio.ensure_future(coro2),
asyncio.ensure_future(coro3)] # 建议使用
# 5.将task任务扔进事件循环对象触发
# 将tasks注册到事件循环中
# 两种方法:asyncio.wait, asyncio.gather
# 第一种方法:asyncio.wait
# loop.run_until_complete(asyncio.wait(tasks)) # wait方法只接受列表作为参数
# 第二种方法:asyncio.gather
loop.run_until_complete(asyncio.gather(*tasks)) # gather方法方法接收不定量参数
for task in tasks:
print('任务返回的结果是:', task.result()) # 获取回调结果
e_time = time.time()
print('总时间:', e_time - s_time)
# =============================================
标签:tasks,协程,Python,---,task,time,wait,asyncio
From: https://www.cnblogs.com/jackchen28/p/18172275