在Python中,控制异步编程的并发可以通过以下几种方式实现:
使用`asyncio.Semaphore`
`Semaphore`是一个同步原语,可以用来限制对共享资源的并发访问数量。在异步编程中,可以使用`asyncio.Semaphore`来控制并发任务的数量。
import asyncio
async def task(semaphore, name):
async with semaphore:
print(f"Task {name} started")
await asyncio.sleep(1)
print(f"Task {name} finished")
async def main():
semaphore = asyncio.Semaphore(3) 限制最多只有3个任务并发执行
tasks = [task(semaphore, f"Task-{i}") for i in range(10)]
await asyncio.gather(*tasks)
asyncio.run(main())
使用`asyncio.Queue`
`Queue`可以用来在生产者和消费者之间安全地传递数据,它内部处理了必要的锁定机制,可以用来控制并发。
import asyncio
async def producer(queue):
for i in range(5):
await queue.put(i)
print(f"Produced {i}")
await asyncio.sleep(1)
async def consumer(queue):
while True:
item = await queue.get()
if item is None:
break
print(f"Consumed {item}")
queue.task_done()
async def main():
queue = asyncio.Queue()
prod_task = asyncio.create_task(producer(queue))
cons_task = asyncio.create_task(consumer(queue))
await prod_task
await queue.join() 等待队列中的所有项都被处理
queue.put(None) 结束消费者协程
await cons_task
asyncio.run(main())
使用`asyncio.gather`
`asyncio.gather`可以用来并发运行多个协程,并等待它们全部完成。
import asyncio
async def task(name):
print(f"Task {name} started")
await asyncio.sleep(1)
print(f"Task {name} finished")
async def main():
tasks = [task(f"Task-{i}") for i in range(5)]
await asyncio.gather(*tasks)
asyncio.run(main())
以上示例展示了如何使用`asyncio.Semaphore`和`asyncio.gather`来控制并发任务的数量和执行。选择合适的方法取决于具体的应用场景和需求