美文网首页
学习asyncio

学习asyncio

作者: 北雁南飞_8854 | 来源:发表于2019-10-20 15:43 被阅读0次

关键字await将控制权移交给event loop。

一、await关键字

async def g():
    # await f()表示暂停函数g()的执行,将控制权移交个event loop,直到
    # 函数f()执行完成、并返回结果。函数g()获取到f()的结果后继续执行。
    # Pause here and come back to g() when f() is ready
    r = await f()
    return r

二、async和await的语法

async def f(x):
    y = await z(x)  # OK - `await` and `return` allowed in coroutines
    return y

async def g(x):
    yield x  # OK - this is an async generator

async def m(x):
    yield from gen(x)  # No - SyntaxError

def m(x):
    y = await z(x)  # Still no - SyntaxError (no `async def` here)
    return y

三、新旧两种语法

import asyncio

@asyncio.coroutine
def py34_coro():
    """Generator-based coroutine, older syntax"""
    yield from stuff()

async def py35_coro():
    """Native coroutine, modern syntax"""
    await stuff()

四、举例

#!/usr/bin/env python3
# countsync.py

import asyncio
import time

async def count(index):
    print("One: " + str(index))
    await asyncio.sleep(1)
    print("Two: " + str(index))

async def main():
    await asyncio.gather(count(0), count(1), count(2))

if __name__ == "__main__":
    s = time.perf_counter()
    asyncio.run(main())
    elapsed = time.perf_counter() - s
    print(f"{__file__} executed in {elapsed:0.2f} seconds.")

输出结果:

One: 0
One: 1
One: 2
Two: 0
Two: 1
Two: 2
count_async.py executed in 1.00 seconds.

相关文章

网友评论

      本文标题:学习asyncio

      本文链接:https://www.haomeiwen.com/subject/odcamctx.html