协程-asyncio模块
asyncio模块
启动单个协程
用法
- 必须要是协程方法
async def demo():
- 阻塞前必须有
await
- 必须创建事件循环
loop = asyncio.get_event_loop()
- 任务执行必须加括号
loop.run_until_complete(demo())
必须先创建一个事件循环:loop = asyncio.get_event_loop()
执行任务:loop.run_until_complete(demo())
import asyncio
# 启动一个任务
async def demo(): # 协程方法
print('start')
await asyncio.sleep(1) # 阻塞
print('end')
loop = asyncio.get_event_loop() # 创建一个事件循环
loop.run_until_complete(demo()) # 把demo任务丢到事件循环中去执行
启动多个协程
启动多个任务,并且没有返回值
先创建事件循环loop = asyncio.get_event_loop()
增加一个wait对象wait_obj = asyncio.wait([demo(),demo(),demo()])
将wait对象丢到事件循环中去loop.run_until_complete(wait_obj)
import asyncio
# 启动多个任务,并且没有返回值
async def demo(): # 协程方法
print('start')
await asyncio.sleep(1) # 阻塞
print('end')
loop = asyncio.get_event_loop() # 创建一个事件循环
wait_obj = asyncio.wait([demo(),demo(),demo()])
loop.run_until_complete(wait_obj)
启动多个任务并且有返回值
先创建事件循环loop = asyncio.get_event_loop()
创建任务对象
t1 = loop.create_task(demo())
t2 = loop.create_task(demo())
tasks = [t1,t2]
增加一个wait对象wait_obj = asyncio.wait(tasks)
将wait对象丢到事件循环中去loop.run_until_complete(wait_obj)
t.result()
获取对应任务的返回值
async def demo(): # 协程方法
print('start')
await asyncio.sleep(1) # 阻塞
print('end')
return 123
loop = asyncio.get_event_loop()
#
t1 = loop.create_task(demo())
t2 = loop.create_task(demo())
tasks = [t1,t2]
wait_obj = asyncio.wait([t1,t2])
#
loop.run_until_complete(wait_obj)
for t in tasks:
print(t.result())
谁先回来先取谁的结果
创建main协程方法
# 谁先回来先取谁的结果
import asyncio
async def demo(i): # 协程方法
print('start')
await asyncio.sleep(10-i) # 阻塞
print('end')
return i,123
async def main():
task_l = []
for i in range(10):
task = asyncio.ensure_future(demo(i))
task_l.append(task)
for ret in asyncio.as_completed(task_l):
res = await ret
print(res)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())