I've been trying to run two asyncio loops in parallel, but I am failing to find meaningful instruction on how to do so. I want to execute two async functions at the same time, while both of them depend on one global variable.
My code looks something like the following:
import asyncio
#a---------------------------------------------------------------
async def foo(n):
print("Executing foo(n)")
return n**2
async def main_a():
print("Executing main_a()")
n = await foo(3)
return n+1
x = 1
async def periodic_a():
global x
i = 0
while True:
i += 2
x = await main_a()
x += i
await asyncio.sleep(1)
#b-----------------------------------------------------------------
async def periodic_b():
global x
while True:
print(f"There are {x} ducks in the pond")
await asyncio.sleep(5)
#execution---------------------------------------------------------
loop = asyncio.get_event_loop()
task = loop.create_task(periodic_a())
try:
loop.run_until_complete(task)
except asyncio.CancelledError:
pass
except KeyboardInterrupt:
task.cancel()
loop.close()
pass
I am trying to get functions periodic_a and periodic_b to run at the same time, and provide the output of print(f"There are {x} ducks in the pond") every five seconds. Thank you in advance for any help!