Skip to content

Instantly share code, notes, and snippets.

@shinkou
Created January 30, 2025 04:18
Show Gist options
  • Save shinkou/246cfb29f317f4cc786734dbcc975868 to your computer and use it in GitHub Desktop.
Save shinkou/246cfb29f317f4cc786734dbcc975868 to your computer and use it in GitHub Desktop.
A short script to demostrate how to use semaphore to manipulate async coroutines
#!/usr/bin/env python3
# -*- vim: set fileencoding=utf-8 ff=unix: -*-
from random import randint
import argparse, asyncio
async def wait4me(semaphore, taskno):
async with semaphore:
waittime = randint(1, 10)
await asyncio.sleep(waittime)
print(f'Task #{taskno} has waited {waittime} seconds.')
return waittime
async def process(n, concurrency):
semaphore = asyncio.Semaphore(concurrency)
tasks = [asyncio.create_task(wait4me(semaphore, i)) for i in range(n)]
results = await asyncio.gather(*tasks)
print(results)
def getargs():
parser = argparse.ArgumentParser(description='Async Semaphore Demo')
parser.add_argument(
'--concurrency',
type=int,
default=4,
help='max number of simultaneous running tasks'
)
parser.add_argument(
'--tasks',
type=int,
default=8,
help='total number of tasks'
)
return parser.parse_args()
if '__main__' == __name__:
args = getargs()
asyncio.run(process(args.tasks, args.concurrency))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment