python-3.x - 插槽可用性的异步队列
问题描述
我正在尝试为有插槽的用户做一个经理。它必须做的是“打开” 10 个插槽,当用户首先制作任务时,它必须检查可用性,如果它是空闲插槽,则用户可以执行任务。
我的意思是,我有 10 个插槽,有 9 个用户在执行任务,因此到达的新用户可以占用最后一个插槽,但如果在此之后有新用户想要执行任务,则会被拒绝。如果用户将来再次询问并且另一个用户已经完成了任务,他将能够做到。
我已经尝试过使用代码
import asyncio
async def worker(name, queue):
while True:
# Get a "work item" out of the queue.
user_id = await queue.get()
# Sleep for 1second.
await asyncio.sleep(1)
# Notify the queue that the "work item" has been processed.
queue.task_done()
print(f'Worker {name} has the user id {user_id}')
async def main():
# Create a queue that we will use to store our "workload".
queue = asyncio.Queue()
# Create worker tasks to process the queue concurrently.
tasks = []
for i in range(10):
task = asyncio.create_task(worker(f'worker-{i}', queue))
tasks.append(task)
# Generate random timings and put them into the queue.
total_sleep_time = 0
for _ in range(2):
await queue.put(_)
await queue.join()
asyncio.run(main())
但是如果没有用户 queue.join() 就不可能运行队列,因此它不会动态修改列表。
对不起我的英语,我希望我已经很好地解释了这个小功能。
非常感谢。
解决方案
推荐阅读
- kubernetes - 无法在 MacOS 上运行 kubectl 命令
- r - 在达到 0 并重置之前列上某些值的平均值
- android - 如何使用应用锁在用户被阻止的应用上显示锁屏
- c# - 如何从 ArcGIS Pro DockPane (WPF) 中获取可调用的 BrowseForFolder 对话框
- db2 - 如何在 java jdbc 应用程序中设置当前查询加速 = ALL?
- xamarin - 动态更改侧面菜单按钮/链接文本颜色 Xamarin.iOS
- kubernetes - Kubernetes 和 Authorization 标头被剥离
- powershell - 打开外网格视图时,我的 Powershell Gui 界面不断调整大小
- javascript - JavaScript 函数只支持最后一个元素(Three.js)
- neural-network - 如何向神经网络呈现整数表示?