Skip to content

uartAvailable() has race condition #5512

@rob-deutsch

Description

@rob-deutsch

Hardware:

Board: DOIT ESP32 DEVKIT v1
Core Installation version: 1_0_6
IDF Version: 3.3.5-1-g85c43024c
IDE name: VS Code with platform.io
Flash Frequency: 40MHz
PSRAM enabled: no
Upload Speed: 115200
Computer OS: macOS

Description:

I am experiencing race conditions with HardwareSerial.available() and HardwareSerial.read(). The following single-threaded code is returning -1 from HardwareSerial.read(), which shouldn't be possible after checking that HardwareSerial.available() > 0.

This seems to be caused by the underlying HAL uartAvailable() function.

Sketch:

//Change the code below by your sketch
#include <Arduino.h>

void setup() {
    Serial.begin(115200);
}

void loop() {
    if (Serial.available() > 0) {
        int b = Serial.read();
        if (b == -1) {
            Serial.println("error reading");
        }
    }
    doOtherStuff()
}

Expected result: Nothing output on serial console
Actual result: Eventually "error reading" output on serial console

Possible cause

This issue seems to be caused by a race condition with the following line:

return (uxQueueMessagesWaiting(uart->queue) + uart->dev->status.rxfifo_cnt) ;

I think that uartAvailable() should turn off interrupts and call UART_MUTEX_LOCK() in order to avoid the race condition.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions