首页 > 解决方案 > 循环后发布 2 个作业的 python asyncio 信号量

问题描述

我需要使用信号量或一些锁来解决两个异步作业的问题。我需要在每个作业的 while 循环中将控制权从一个传递到另一个。第一个作业永远运行,第二个作业最终将完成。

async def my_worker1(semaphore):
    n = random.randint(2, 10)
    while n > 0:
        n -= 1
        async with semaphore:
            print("Acquired the worker 1")
            await asyncio.sleep(2)
            print("Releasing worker 1")


async def my_worker2(semaphore):
    while True:
        async with semaphore:
            print("Acquired the worker 2")
            await asyncio.sleep(2)
            print("Releasing worker 2")


async def main():
    my_semaphore = asyncio.Semaphore()
    await asyncio.wait([my_worker1(my_semaphore), my_worker2(my_semaphore)])


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
print("All Workers Completed")
loop.close()

但是在我的代码中,只有两个工作中的一个工作,并且在当前工作完成之前不会释放信号量。

Acquired the worker 2
Releasing worker 2
Acquired the worker 2
Releasing worker 2
Acquired the worker 2
Releasing worker 2
...

我需要这样的东西:

Acquired the worker 2
Releasing worker 2
Acquired the worker 1
Releasing worker 1
Acquired the worker 1
Releasing worker 1
Acquired the worker 2
Releasing worker 2
...

对不起,如果我的问题不够清楚。

标签: pythonsemaphore

解决方案


我发现了如何解决这个任务。问题是我没有await可以在每次循环后将控制权传递给另一个工人的结构。工作代码如下所示:

async def my_worker1(semaphore):
    n = random.randint(2, 10)
    while n > 0:
        n -= 1
        async with semaphore:
            print("Acquired the worker 1")
            await asyncio.sleep(2)
            print("Releasing worker 1")
        await asyncio.sleep(0) # <---


async def my_worker2(semaphore):
    while True:
        async with semaphore:
            print("Acquired the worker 2")
            await asyncio.sleep(2)
            print("Releasing worker 2")
        await asyncio.sleep(0) # <---

推荐阅读