异步调用,加信号量控制并发数的demo代码
import asyncio
async def my_coroutine(task_id, semaphore):
async with semaphore: # 这里会等待信号量的许可
print(f"Task {task_id} started")
await asyncio.sleep(1) # 模拟耗时操作
print(f"Task {task_id} finished")
return f"Result of task {task_id}"
async def main():
max_concurrency = 3 # 设置最大的并发数为3
semaphore = asyncio.Semaphore(max_concurrency)
tasks = [my_coroutine(i, semaphore) for i in range(10)]
results = await asyncio.gather(*tasks)
print("All tasks completed:", results)
# 运行主协程
asyncio.run(main())
浙公网安备 33010602011771号