← index #7471Issue #6893
Related · medium · value 2.137
QUERY · ISSUE

Incorrect uasyncio behaviour: tasks are not correctly terminated

openby mattytrentiniopened 2021-06-29updated 2021-07-05
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

closedby peterhinchopened 2021-02-13updated 2024-09-13

[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())

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied