简体   繁体   中英

python asyncio semaphore for 2 jobs release after loop

I need to solve a problem with two asynchronous jobs using semaphore or some lock. I need to pass control from one to another in while loops for each jobs. The first job runs forever and the second job will be eventually finished.

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()

But in my code works only one of two jobs and doesn't release semaphore before current job will be finished.

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

And I need something like this:

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
...

Sorry if my question is not enough clear.

I found out how to resolve this task. Problem is I didn't have await construction where I could pass control to another worker after every loop. Working code looks like that:

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) # <---

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM