Skip to content

fix(coro): global_switch runs on and off under a mutex - #20

Merged
codethinki merged 1 commit into
masterfrom
fix/global-switch-mutex
Oct 21, 2026
Merged

codethinki merged 1 commit into
masterfrom
fix/global-switch-mutex

Conversation

@codethinki

Copy link
Copy Markdown
Owner

The atomic counter alone was not thread safe and not exception safe.

Problems:

  • a second `acquire()` returned while the first one was still inside `on`, so the caller used the global state before it existed
  • `on` could start while a last `release()` was still inside `off`
  • a throw of `on` left the count at 1: `acquired()` was true, and the next `acquire()` did not call `on` again

Fix:

  • `acquire()`, `release()` and `force_off()` run under a `std::mutex`
  • the count increments after `on` returns
  • the count stays atomic, so `acquire_count()` and `acquired()` stay lock free
  • `on` and `off` must not call the switch, the mutex is not recursive (doc)

Tests: 5 new tests in `global_switch_test.cpp`. The 3 tests for the problems fail with the old code.

Found while using the switch for the vulkan loader in cth_engine.

- an acquire returns after on finished, on and off never overlap
- a throw of on leaves the count unchanged, the next acquire calls on again
- tests for the three cases, they fail with the old atomic counter
@codethinki
codethinki enabled auto-merge (squash) October 21, 2026 11:10
@codethinki
codethinki merged commit 9e94b4a into master Oct 21, 2026
6 checks passed
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