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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值