Created
June 7, 2016 07:24
-
-
Save harrisont/2692e2e5b15ef873c5cb1f210f35cc47 to your computer and use it in GitHub Desktop.
Limit the number of running futures with asyncio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from contextlib import closing | |
import random | |
async def async_index_printer(index: int): | |
print('start', index) | |
await asyncio.sleep(random.uniform(1, 3)) | |
return index | |
async def do_with_semaphore(semaphore: asyncio.Semaphore, future): | |
async with semaphore: | |
return await future | |
async def async_index_printer_with_finisher(): | |
semaphore = asyncio.Semaphore(2) | |
futures = [do_with_semaphore(semaphore, async_index_printer(i)) for i in range(5)] | |
for completed_future in asyncio.as_completed(futures): | |
result = await completed_future | |
print('end', result) | |
def main(): | |
with closing(asyncio.get_event_loop()) as loop: | |
loop.set_debug(True) | |
future = async_index_printer_with_finisher() | |
loop.run_until_complete(future) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment