2016-12-20 38 views
1

必要時,使用主循環運行協程來完成某些操作。並從中啓動另一個協程,不會阻塞。使用Python 3.5asyncio如何在運行循環中運行其他協同例程中的獨立協同例程.Python 3.5

import asyncio,time 
async def cor1(): 
    for i in range(10): 
     await asyncio.sleep(0) 
     print("cor1",i) 

async def cor2(): 
    for i in range(10): 
     await asyncio.sleep(0) 
     time.sleep(1) 
     print("cor2",i) 

async def main(): 
    asyncio.ensure_future(cor1()) 
    asyncio.ensure_future(cor2()) 
    print("cor3") 

loop = asyncio.get_event_loop() 
asyncio.ensure_future(main()) 
loop.run_forever() 

現在主循環會創建兩個協程,但它們並不是一個接一個地並行運行。在某人完成之前,另一個人不會開始工作。當然,您可以在不同的線程上運行它們並使用隊列建立通信。但有可能在Python 3.5

回答

0

這是一種與ASYNCIO的幫助下做到這一點你怎麼可以並行運行它們:

import asyncio 

async def cor1(): 
    for i in range(10): 
     await asyncio.sleep(1) 
     print("cor1", i) 

async def cor2(): 
    for i in range(10): 
     await asyncio.sleep(1) 
     print("cor2", i) 

loop = asyncio.get_event_loop() 
cors = asyncio.wait([cor1(), cor2()]) 
loop.run_until_complete(cors) 

注意,time.sleep(1)(不像asyncio.sleep(1))是一個阻塞調用和不會同時運行。

Luciano Ramalho的書流利的Python有一個很好的章節關於協程和asyncio ......以防萬一。

+0

謝謝。儘管我沒有看到特別的區別。 time.sleep(1),我的意思是執行一個長期的操作。在你的例子中,當一個函數沒有完成它的動作時,另一個開始沒有效果。我的目標是實現並行執行 –

+0

if您需要並行執行您需要的阻塞任務[線程](https://docs.python.org/3/library/threading.html?highlight=threading#module-threading)或[multiprocessing](https:// docs .python.org/3 /庫/ multiprocessing.html?高亮=多#模塊多處理)。 asyncio就像'合作多任務'一樣;你所有的任務都需要協同併產生CPU時間。 –

1

這個決定讓我

import asyncio,time 
from concurrent.futures import ProcessPoolExecutor 
def cor1(): 
    for i in range(10): 
     print("cor1", i) 
     time.sleep(2) 

def cor2(): 
    for i in range(10): 
     print("cor2", i) 
     time.sleep(1) 

executor = ProcessPoolExecutor(2) 
loop = asyncio.get_event_loop() 

asyncio.ensure_future(loop.run_in_executor(executor, cor1)) 
asyncio.ensure_future(loop.run_in_executor(executor, cor2)) 

loop.run_forever() 
相關問題