2016-03-04 56 views
2

我想圍繞在Python3中出現的新asyncio函數。異步def和協程,什麼是鏈接

我從計算器上發現了一個簡單的例子工人開始,修改了一下:

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() ...它是對委派的佔位符,但阻止功能?它在哪裏屈服?)

但是,首先,我怎麼能轉換這個例子使用新花式async defawait關鍵字?收益會是什麼?

回答

2

只是

async def f(arg) 

yield from在代碼中await更換

@asyncio.coroutine 
def f(arg) 

也讀PEP 412async withasync for