想要提供可以进行协程切换的awaitable,可以使用下面的方法:
1 任务task
async def func():
print("yes Wait")
task = asyncio.create_task(func())
await task
2 协程对象,可以使async def 定义的协程函数(是否能触发切换不一定,要看函数内容)
函数内可以利用asyncio.sleep(0) # https://docs.python.org/zh-cn/3/library/asyncio-task.html#sleeping
该函数可以实现协程切换
3 asyncio.sleep(0).__await__()
只好借用已经实现的__await__()
并发执行协程
可以如下:
loop = asyncio.get_event_loop()
tasks = [greenlet_func(x) for x in ["name", "key"]]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
也可以:
async def func():
await asyncio.sleep(0)
return "yes"
async def main(x):
print(x)
print(await func())
async def run():
await asyncio.gather(main("VV"), main("NN"), main("MM"))
asyncio.run(run())
标签:task,协程,await,func,async,asyncio
From: https://www.cnblogs.com/haiton/p/15098840.html