Reputation: 23
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!
Upvotes: 2
Views: 3498
Reputation: 2733
You should create two tasks for each function you want to run concurrently and then await them with asyncio.gather
. Also note you should use asyncio.run
instead of using the event loop directly, this will make your code cleaner as it handles creating and shutting down the loop for you. Modify the execute section of your code the the following:
async def main():
periodic_a_task = asyncio.create_task(periodic_a())
periodic_b_task = asyncio.create_task(periodic_b())
await asyncio.gather(periodic_a_task, periodic_b_task)
asyncio.run(main())
Also note you mention multiple processes, but there isn't any need to use multiprocessing in the example you're describing. If you do need multiprocessing, you'll need a different approach for global data with shared memory.
Upvotes: 0