← index #9233Issue #6893
Related · medium · value 1.584
QUERY · ISSUE

uasyncio StreamWriter concurrency failure

openby peterhinchopened 2022-09-07updated 2022-09-13
enhancementport-stm32

The following script produces unexpected behaviour on a Pyboard 1.1

import uasyncio as asyncio
from machine import UART
import monitor
from pyb import LED
led = LED(1)

uarts = []  # Pins x9, x3, y9, y1
for n in (1, 2, 3, 6):
    uarts.append((UART(n, 9600, timeout=0), n))

async def sender(u, n):
    s = f"Hello from UART {n} "# * 55  # 990 chars
    swriter = asyncio.StreamWriter(u, {})
    while True:
        swriter.write(s)
        await swriter.drain()
        await asyncio.sleep(0)

async def heartbeat():
    while True:
        await asyncio.sleep_ms(100)
        led.toggle()

async def main():
    for v in uarts:
        asyncio.create_task(sender(*v))
    await heartbeat()

asyncio.run(main())

Each instance of swriter.drain appears to block: here is no concurrency.
Image

With 990 character strings (see code comment), the heartbeat LED changes state only once per second, implying that the scheduler is locked for the duration of each write. The LA trace is similar to above, but each burst is ~1s long.

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