« Back to Index

[Python Semaphore]

View original Gist on GitHub

Tags: #python #concurrency #semaphore

Python Semaphore.py

import asyncio

async def do_work(semaphore):
    # new: only enter if semaphore can be acquired
    async with semaphore:
        print("start work")
        await asyncio.sleep(1) # optionally do a lot of work that will consume memory
        print("end work")

async def main():
    tasks = []
    
    # new: instantiate a semaphore before calling our coroutines
    semaphore = asyncio.BoundedSemaphore(10)
    
    for i in range(100):
        # new: pass the semaphore to the coroutine that will limit itself
        tasks.append(asyncio.ensure_future(do_work(semaphore)))
        
    await asyncio.gather(*tasks)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.set_debug(True)
    loop.run_until_complete(main())