Issue
How to await while loop? I have the following code snippet:
import asyncio
from asyncio.tasks import sleep
import time
running = True
async def f1():
global running
print(f"Running: {running}")
print("f1() started.")
### await the while loop below
while running:
print(f"Inside while loop")
###
print(f"Running: {running}")
print("f1() ended")
async def f2():
global running
print("f2() started.")
# this should be blocking code
time.sleep(0.5)
print("f2 ended.")
running = False
async def main():
await asyncio.gather(f1(), f2())
asyncio.run(main())
Basically, what I want is:
# 1. Start f1(). f1() has a while loop.
# 2. Start f2().
# 3. Notify f1() to break the while loop.
Solution
I guess you have to put in some await asyncio.sleep(0)
or so into the while loop
, not sure if it works with 0
but just put a small number. It just has to be some await call that gives others the chance to do
import asyncio
from asyncio.tasks import sleep
import time
running = True
async def f1():
global running
print(f"Running: {running}")
print("f1() started.")
### await the while loop below
while running:
print(f"Inside while loop")
await asyncio.sleep(0)
###
print(f"Running: {running}")
print("f1() ended")
async def f2():
global running
print("f2() started.")
# this should be blocking code
time.sleep(0.5)
print("f2 ended.")
running = False
async def main():
await asyncio.gather(f1(), f2())
asyncio.run(main())
that works for me
Answered By - Simon Hawe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.