python - 在 Python 中使用带有 asyncio 的信号量
问题描述
我试图限制使用信号量运行的同时异步函数的数量,但我无法让它工作。我的代码归结为:
import asyncio
async def send(i):
print(f"starting {i}")
await asyncio.sleep(4)
print(f"ending {i}")
async def helper():
async with asyncio.Semaphore(value=5):
await asyncio.gather(*[
send(1),
send(2),
send(3),
send(4),
send(5),
send(6),
send(7),
send(8),
send(9),
send(10),
])
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(helper())
loop.close()
输出是:
starting 1
starting 2
starting 3
starting 4
starting 5
starting 6
starting 7
starting 8
starting 9
starting 10
ending 1
ending 2
ending 3
ending 4
ending 5
ending 6
ending 7
ending 8
ending 9
ending 10
我希望并期望只有 5 个会同时运行,但是所有 10 个会同时启动和停止。我究竟做错了什么?
解决方案
请在下面找到工作示例,请随时提出问题:
import asyncio
async def send(i: int, semaphore: asyncio.Semaphore):
# to demonstrate that all tasks start nearly together
print(f"Hello: {i}")
# only two tasks can run code inside the block below simultaneously
async with semaphore:
print(f"starting {i}")
await asyncio.sleep(4)
print(f"ending {i}")
async def async_main():
s = asyncio.Semaphore(value=2)
await asyncio.gather(*[send(i, semaphore=s) for i in range(1, 11)])
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(async_main())
loop.close()
推荐阅读
- java - 如何使用 jolt 替换某些属性的文本
- tensorflow - 如何摆脱 Keras 指标名称的 _N?
- r - 在 r 中使用 keras 中的 layer_dense 进行神经网络配置
- html - 如何在不使用 CSS 移动文本的情况下相对于文本定位图像?
- c++ - for(;;) vs do..while() 用于主程序循环
- angular - Angular 7:使用查询参数刷新页面导致路径不匹配
- java - 为什么我的循环输出两个不同的结果?
- jquery - 如何使用 jquery 删除输入数据?
- javascript - 如何用变量替换 HTML 元素的所有实例(或更简单的方法)
- r - 从闪亮下载