Coconutcake
Coconutcake

Reputation: 196

two async tasks - one depends on another in python

I need to write a code where i need to to check in real time a status of some variable. I decited to use asyncio to create two async def functions

import asyncio

async def one():
    global flag
    flag = True
    while flag == True:
        await asyncio.sleep(0.2)
        print("Doing one")

async def two():
    await asyncio.sleep(2)
    global flag
    flag = False

async def main():
    tasks = []
    tasks.append(one())
    tasks.append(two())
    await asyncio.gather(*tasks)

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
finally:
    loop.close()
    print("Loop ended")

When loop starts, all tasks has been lauched and after 2 seconds def two() sets flag=False, which stops def one(). It's good but i want def one() to perform while loop without await asyncio.sleep(0.2) becouse i dont want to have real live update so i set await asyncio.sleep(0.0). Is it a good practice?

Upvotes: 2

Views: 1205

Answers (1)

felipe
felipe

Reputation: 8025

Using a global variable is indeed bad practice. What you are looking for is asyncio's primitives, specifically the asyncio.Event primitive. Here is what you are doing, but with asyncio.Event:

import asyncio

async def one(event):
    while event.is_set() == False:
        await asyncio.sleep(0.5)
        print("Hello World!")

async def two(event):
    await asyncio.sleep(2)
    event.set()

async def main():
    event = asyncio.Event()
    await asyncio.gather(*[one(event), two(event)])

asyncio.run(main())

Upvotes: 2

Related Questions