QUERY · ISSUE
Incorrect uasyncio behaviour: tasks are not correctly terminated
extmod
(First reported on the forum)
The following snippet:
try:
import uasyncio as asyncio
except ImportError:
import asyncio
async def count():
i = 0
while True:
print(i)
i += 1
await asyncio.sleep(1)
async def main():
asyncio.create_task(count())
await asyncio.sleep(5)
asyncio.run(main())
asyncio.run(main())
Produces the following in CPython:
0
1
2
3
4
0
1
2
3
4
But in MicroPython:
0
1
2
3
4
0
5
1
6
2
7
3
8
4
9
It appears that tasks are not correctly terminated (?).
A workaround that produces the correct output is to run the second task in a second event loop:
try:
import uasyncio as asyncio
except ImportError:
import asyncio
async def count():
i = 0
while True:
print(i)
i += 1
await asyncio.sleep(1)
async def main():
asyncio.create_task(count())
await asyncio.sleep(5)
asyncio.run(main())
asyncio.new_event_loop() # Added line
asyncio.run(main())
Note that running either of the snippets repeatedly causes more confusing output because all previous tasks are still running on the queue.
CANDIDATE · ISSUE
uasyncio Event unexpected behaviour with only one task
[EDIT] Apologies, @kevinkk525 has pointed out that this is a duplcate of https://github.com/micropython/micropython/issues/5843
This prints "start" then runs to completion where I would expect it to wait indefinitely on the Event:
import uasyncio as asyncio
evt = asyncio.Event()
async def main_loop():
while True:
print("start")
await evt.wait()
await asyncio.sleep(1)
print("Got event")
asyncio.run(main_loop())
If an additional task is running the main_loop task behaves as expected, waiting forever:
import uasyncio as asyncio
evt = asyncio.Event()
async def main_loop():
while True:
print("start")
await evt.wait()
await asyncio.sleep(1)
print("Got event")
async def main():
asyncio.create_task(main_loop())
while True:
await asyncio.sleep(1)
asyncio.run(main())