From bb7a15f43611803484c45bca0f62b6738016786a Mon Sep 17 00:00:00 2001 From: Aleksandrs Sevastjanovs Date: Fri, 30 Oct 2026 18:07:21 +0200 Subject: [PATCH] Stop flserial's SerialThread spinning on an idle serial port POSIX opens the port O_NONBLOCK with VMIN/VTIME=0, and fl_open skips setTimeout on Linux/macOS, so the default all-zero Timeout makes SerialThread's read() return immediately. With no traffic the reader spins at 100% of a core for the whole session. Release builds and a minimized window do not help because it is a native thread. Set a 10 ms read/select timeout on POSIX. Data still wakes select immediately; the timeout only bounds idle wakeups and queued-write latency. Apply the same change to the macOS copy of flserial. Follow-up to #557. Measured with a PTY harness, idle: 99.9% of one core before, 0.2% after. RX and TX still pass. --- third_party/flserial/macos/Classes/flserial.cpp | 7 ++++++- third_party/flserial/src/flserial.cpp | 7 ++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/third_party/flserial/macos/Classes/flserial.cpp b/third_party/flserial/macos/Classes/flserial.cpp index ec30afc7..34e99ab2 100644 --- a/third_party/flserial/macos/Classes/flserial.cpp +++ b/third_party/flserial/macos/Classes/flserial.cpp @@ -154,7 +154,12 @@ FFI_PLUGIN_EXPORT int fl_open(int flh, char *portname, int baudrate) port->serialport = new serial::Serial(); #if !defined(__linux__) && !defined(__APPLE__) port->serialport->setTimeout(serial::Timeout(0, 2, 0, 0, 0)); -#endif // #if defined(__linux__) +#else + // With a zero read timeout, read() returns immediately on an idle + // O_NONBLOCK port and SerialThread spins. A short timeout lets select() + // sleep; arriving data still wakes it immediately. + port->serialport->setTimeout(10, 10, 0, 0, 0); +#endif port->serialport->setPort(portname); port->serialport->setBaudrate(baudrate); diff --git a/third_party/flserial/src/flserial.cpp b/third_party/flserial/src/flserial.cpp index a58206e6..ebdf2b2f 100644 --- a/third_party/flserial/src/flserial.cpp +++ b/third_party/flserial/src/flserial.cpp @@ -167,7 +167,12 @@ FFI_PLUGIN_EXPORT int fl_open(int flh, char *portname, int baudrate) port->serialport = new serial::Serial(); #if !defined(__linux__) && !defined(__APPLE__) port->serialport->setTimeout(serial::Timeout(0, 2, 0, 0, 0)); -#endif // #if defined(__linux__) +#else + // With a zero read timeout, read() returns immediately on an idle + // O_NONBLOCK port and SerialThread spins. A short timeout lets select() + // sleep; arriving data still wakes it immediately. + port->serialport->setTimeout(10, 10, 0, 0, 0); +#endif port->serialport->setPort(portname); port->serialport->setBaudrate(baudrate);