首页 > 解决方案 > 插槽可用性的异步队列

问题描述

我正在尝试为有插槽的用户做一个经理。它必须做的是“打开” 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() 就不可能运行队列,因此它不会动态修改列表。

对不起我的英语,我希望我已经很好地解释了这个小功能。

非常感谢。

标签: python-3.xpython-asyncio

解决方案


推荐阅读