async def and coroutines, what's the link
I'm trying to wrap my head around the new asyncio functionnalities which appeared in Python3.
I started from a simple worker example found on stackoverflow, modified a bit :
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()
I mostly understand how it works (except perhaps for the yield from asyncio.sleep()
... Is it a placeholder for a delegated, but blocking function ? Where does it yield to ?)
But, above all, how could I transform this example to use the new fancy async def
and await
keywords ? And what would be the gain ?
Just replace
@asyncio.coroutine
def f(arg)
with
async def f(arg)
and yield from
with await
in your code.
Also read PEP 412 about async with
and async for
.
This article is what I found to be the most helpful.
http://www.snarky.ca/how-the-heck-does-async-await-work-in-python-3-5
链接地址: http://www.djcxy.com/p/53226.html上一篇: 如何在异步协程中包装同步函数?