python-Advanced Concurrent Programming-Advanced Usage of asyncio (II)
最编程
2024-06-09 09:27:22
...
Timeout
Timeout 是 asyncio 中的一个概念,它代表一个超时时间。我们可以使用 asyncio.wait_for() 方法设置协程任务的超时时间,从而避免协程任务无限阻塞。
下面是一个使用 asyncio.wait_for() 方法设置协程任务超时时间的示例:
import asyncio
async def coroutine():
print("Coroutine start")
await asyncio.sleep(10)
print("Coroutine end")
async def main():
try:
await asyncio.wait_for(coroutine(), timeout=3)
except asyncio.TimeoutError:
print("Coroutine timeout")
if __name__ == "__main__":
asyncio.run(main())
在上述示例中,我们使用 asyncio.wait_for() 方法设置了协程任务的超时时间为 3 秒。如果协程任务在超时时间内未完成,将抛出 asyncio.TimeoutError 异常。
Semaphore
Semaphore 是 asyncio 中的一个概念,它代表一种计数信号量。我们可以使用 asyncio.Semaphore 类实现协程任务的并发控制,从而避免资源的竞争和浪费。
下面是一个使用 asyncio.Semaphore 类实现协程任务的并发控制的示例:
import asyncio
async def coroutine(semaphore):
async with semaphore:
print("Coroutine start")
await asyncio.sleep(1)
print("Coroutine end")
async def main():
semaphore = asyncio.Semaphore(2)
tasks = [asyncio.create_task(coroutine(semaphore)) for i in range(5)]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
在上述示例中,我们使用 asyncio.Semaphore 类创建了一个 Semaphore 对象,其值为 2。然后,我们使用 asyncio.create_task() 方法创建了 5 个协程任务,并使用 asyncio.gather() 方法等待它们的执行。在协程任务中,我们使用 async with 语句获取 Semaphore 对象的锁,并实现了协程任务的并发控制。