0
点赞
收藏
分享

微信扫一扫

Python编程:协程async和await


Python 3.5

把@asyncio.coroutine替换为async;
把yield from替换为await

用asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作。

以下两种写法等价

@asyncio.coroutine
def hello():
print("Hello world!")
r = yield from asyncio.sleep(1)
print("Hello again!")

python3.5

async def hello():
print("Hello world!")
r = await asyncio.sleep(1)
print("Hello again!")

协程示例

import asyncio
import time

now = lambda : time.time()

async def hello():
print("hello")
await asyncio.sleep(2)
return "done"

start = now()

# 协程对象
h1 = hello()
h2 = hello()
h3 = hello()

# 创建一个事件loop
loop = asyncio.get_event_loop()

# 任务(task)对象
tasks = [
asyncio.ensure_future(h1),
asyncio.ensure_future(h2),
asyncio.ensure_future(h3),
]

# 将协程加入到事件循环loop
loop.run_until_complete(asyncio.wait(tasks))

for task in tasks:
print(task.result())

print(now()-start)
"""
hello
hello
hello
done
done
done
2.005011796951294
"""


参考


  1. ​​廖雪峰pyhton -async/await​​
  2. ​​python中重要的模块–asyncio​​




举报

相关推荐

0 条评论