async def和coroutines,链接是什么

我试图围绕在Python3中出现的新的asyncio函数来解决问题。

我从一个在stackoverflow上找到的简单工人例子开始,修改了一下:

import asyncio, random

q = asyncio.Queue()

@asyncio.coroutine
def produce(name):
    while True:
        value = random.random()
        yield from q.put(value)
        print("Produced by {0}".format(name))
        yield from asyncio.sleep(1.0 + random.random())

@asyncio.coroutine
def consume(name):
    while True:
        value = yield from q.get()
        print("Consumed by {0} ({1})".format(name, q.qsize()))
        yield from asyncio.sleep(1.2 + random.random())

loop = asyncio.get_event_loop()
loop.create_task(produce('X'))
loop.create_task(produce('Y'))
loop.create_task(consume('A'))
loop.create_task(consume('B'))
loop.run_forever()

我主要了解它是如何工作的(除了可能yield from asyncio.sleep()yield from asyncio.sleep() ...它是一个委托,但阻塞函数的占位符?它在哪里屈服?)

但是,最重要的是,我怎么能转换这个例子来使用新的async defawait关键字? 收益会是什么?


只需更换

@asyncio.coroutine
def f(arg)

async def f(arg)

yield from您的代码中await

同时阅读关于async withasync for PEP 412。


这篇文章是我发现最有用的。

http://www.snarky.ca/how-the-heck-does-async-await-work-in-python-3-5

链接地址: http://www.djcxy.com/p/53225.html

上一篇: async def and coroutines, what's the link

下一篇: how to cache asyncio coroutines