一種選擇是使用asyncio.Semaphore
:
import asyncio
import random
s = asyncio.Semaphore(5)
async def my_coroutine(i):
async with s:
print("start", i)
await asyncio.sleep(random.uniform(1, 3))
print("end", i)
loop = asyncio.get_event_loop()
tasks = [my_coroutine(i + 1) for i in range(50)]
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
更新:concurrent.futures
可能會解決你的問題比asycnio一個更簡單的方法,因爲執行者有一個非常簡單max_workers說法:
import concurrent.futures
import time
import random
def my_routine(i):
print("start", i)
# Here you can use subprocess.* for anything, instead we will sleep:
time.sleep(random.uniform(1, 3))
print("end", i)
return "i={}".format(i)
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
jobs = {executor.submit(my_routine, i + 1) for i in range(50)}
for fut in concurrent.futures.as_completed(jobs):
print(fut.result())
print('done')
來源
2017-01-07 08:27:26
Udi
你想'asyncio'使用'multiporcessing'?如果是這樣的話:我試着用踏板;不完全相同,但可能會讓你知道如何到達那裏, –
我不想用asyncio進行多處理。我試圖調用一個外部進程...另一種方式來說明:我想要併發性,而不是並行性。 –
對不起,我很困惑... asyncio會在單個線程上運行;無需擔心有限的資源。 otoh:啓動進程*將*導致並行性(不是併發性)。那是哪個呢?你可以發佈你的協同程序的玩具例子嗎? (我會對你如何「等待」你開始的一個過程感興趣)。 –