Skip to content

fix: data races on loop status, io state flags and hrtime under tsan - #888

Open
aleksisch wants to merge 1 commit into
ithewei:masterfrom
aleksisch:fix-tsan-data-races
Open

aleksisch wants to merge 1 commit into
ithewei:masterfrom
aleksisch:fix-tsan-data-races

Conversation

@aleksisch

@aleksisch aleksisch commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes data races reported by ThreadSanitizer when hio_write/hio_close are called from a non-loop thread (both are documented as thread-safe).

Changes

  • hio_s: ready, connected, closed are now atomic_bool instead of bitfield bits. They are read without a lock from other threads, while the loop thread rewrites neighbouring bits in the same word.
  • hio_s: last_read_hrtime / last_write_hrtime and hloop_s::cur_hrtime are now atomic_ullong, since hio_write stamps last_write_hrtime from cur_hrtime on the caller's thread.
  • hloop_s::status is now atomic_int.
    • hloop_run stores RUNNING after setting pid/tid, so hloop_stop sees a valid tid.
    • hloop_stop sets STOP (via new hatomic_exchange) before the wakeup. Before, the loop could wake, still see RUNNING, and block again.
  • base/hatomic.h: add ATOMIC_EXCHANGE / hatomic_exchange for C11, C++, GCC __sync, Win32 and a non-atomic fallback.

sizeof(struct hio_s) grows from 424 to 432 on linux-x64.

hio_write/hio_close are documented thread-safe, but they read io->ready/closed
unlocked while the loop thread rewrites neighbouring bits of the same bitfield
word, and hio_write stamps last_write_hrtime from the loop's cur_hrtime. Make
those fields atomic, and make loop->status atomic, stored before hloop_stop's
wakeup so the woken loop sees STOP. Found with ThreadSanitizer.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant