Issue
I need to run a program about 500 times with different inputs.
I'd like to use asyncio.create_subprocess_exec
and want to limit the number of processes running at the same time so as not to clog up the machine.
Is there a way to set the concurrency level? For example, I'd expect something like AbstractEventLoop.set_max_tasks
.
Solution
As suggested by @AndrewSvetlov, you can use an asyncio.Semaphore
to enforce the limit:
async def run_program(input):
p = await asyncio.create_subprocess_exec(...)
# ... communicate with the process ...
p.terminate()
return something_useful
async def run_throttled(input, sem):
async with sem:
result = await run_program(input)
return result
LIMIT = 10
async def many_programs(inputs):
sem = asyncio.Semaphore(LIMIT)
results = await asyncio.gather(
*[run_throttled(input, sem) for input in inputs])
# ...
Answered By - user4815162342
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.