Skip to content

__cxa_guard_acquire does not work WASM Workers (depends on pthread functions) #26277

Description

@AndreyRepko

When using -sWASM_WORKERS, C++ static local variable initialization (__cxa_guard_acquire) can busy-spin indefinitely if two workers trigger the same static init simultaneously. It seems to be caused by libcxxabi getting the GlobalMutex model, while pthread functions are basically stubs

The problem is a mismatch between how libcxxabi and libc are built for WASM Workers:

  • libcxxabi is compiled without _LIBCXXABI_HAS_NO_THREADS (because is_ww=True in system_libs.py:1753), so __cxa_guard_acquire uses the GlobalMutex implementation that calls pthread_mutex_lock() / pthread_cond_wait()
  • But libc links library_pthread_stub.c (because is_mt=False), where these are all noops returning 0

So when Worker A starts initializing a static (sets PENDING_BIT) and Worker B comes along, Worker B enters the condvar wait loop in cxa_guard_impl.h — but pthread_cond_wait returns immediately, so it becomes a tight busy-spin until Worker A finishes.

We hit this in practice with thread_local std::optional<T> (non-trivial destructor) — first access triggers __cxa_thread_atexit → static DtorsManager manager → __cxa_guard_acquire. Our tests time out when multiple WASM Workers start executing the same startup function simultaneously.

Version of emscripten/emsdk: We are using 4.0.20 (as for the LLVM bug), but it seems the same code on main.

Proposed fix:

The InitByteFutex implementation already exists in cxa_guard_impl.h and uses only futex wait/wake — no pthread at all. WASM has native futex support via __builtin_wasm_memory_atomic_wait32 / __builtin_wasm_memory_atomic_notify. The fix is to wire these in:

system/lib/libcxxabi/src/cxa_guard_impl.h — add before the #else nullptr fallback (after the SYS_futex block):

#elif defined(__EMSCRIPTEN__) && defined(__EMSCRIPTEN_SHARED_MEMORY__)
void PlatformFutexWait(int* addr, int expect) {
  __builtin_wasm_memory_atomic_wait32(addr, expect, -1);
}
void PlatformFutexWake(int* addr) {
  __builtin_wasm_memory_atomic_notify(addr, __INT_MAX__);
}

tools/system_libs.py — in class libcxxabi.get_cflags(), select the futex implementation for WASM Workers:

    if not self.is_mt and not self.is_ww:
      cflags.append('-D_LIBCXXABI_HAS_NO_THREADS')
    elif self.is_ww:
      cflags.append('-D_LIBCXXABI_USE_FUTEX')

Setting _LIBCXXABI_HAS_NO_THREADS instead looks very dangerous.

Side note: as we don't have TLS destructors for WASM Workers, the __cxa_thread_atexit registration that triggers this is effectively dead code — but that's a separate issue.

Activity

  1. added a commit that references this issue on Feb 16, 2026
    7f8170b
  2. sbc100 commented on Feb 16, 2026

    @sbc100
    Collaborator

    Seems reasonable. Kind of sad we have to hack libc++ at this very low level. I worry about how to verify the correctness of this new PlatformFutexWait implementation and the cost of maintaining it overtime as a patch to libc++.

    I also fear there there could more more issue like this hiding in place like libc and libc++ where.

    But feel free to send a PR since the status quo is clearly broken.

    BTW, in your case why did you choose to use wasm workers over pthreads?

  3. AndreyRepko commented on Feb 16, 2026

    @AndreyRepko
    Author

    I think the main reason is that we have much more control over WASM workers and code in general, and it is much more lightweight. We do not want any C++ code to use threads without our task scheduler, and we do not have legacy code that requires or uses pthreads. I wrote a solution based on pthreads first, but the WASM workers' solution looks much more elegant and lean.

    It seems like this line can cause trouble (trap) if called from the main thread
    __builtin_wasm_memory_atomic_wait32(addr, expect, -1);

    And it seems like we can't easily check for the main thread there.

    So it might be that this fix can introduce another error.

    Has it been considered implementing stubs (pthread_mutex_lock / pthread_cond_wait) for Wasm Workers, or is that the opposite of the idea of them?

  4. sbc100 commented on Feb 16, 2026

    @sbc100
    Collaborator

    I think the main reason is that we have much more control over WASM workers and code in general, and it is much more lightweight. We do not want any C++ code to use threads without our task scheduler, and we do not have legacy code that requires or uses pthreads. I wrote a solution based on pthreads first, but the WASM workers' solution looks much more elegant and lean.

    Is that just a feeling you got or were you able to measure impact? I'm curious if you any numbers (either performance or code size) and if we there are large gaps maybe we can work on improving the pthread implementation in certain areas.

    It seems like this line can cause trouble (trap) if called from the main thread __builtin_wasm_memory_atomic_wait32(addr, expect, -1);

    And it seems like we can't easily check for the main thread there.

    So it might be that this fix can introduce another error.

    Has it been considered implementing stubs (pthread_mutex_lock / pthread_cond_wait) for Wasm Workers, or is that the opposite of the idea of them?

    Yes, I think that is kind of exactly that opposite of idea of wasm workers. Pthread mutex's have a lot of complex modes of operation which I think is what @juj was trying to get away from with wasm workers.

  5. added a commit that references this issue on Feb 17, 2026
    0dc7e17
  6. AndreyRepko commented on Feb 17, 2026

    @AndreyRepko
    Author

    It's hard for me to distinguish the impact of shared memory support from the pthread impact. Pthreads are bringing a lot of JS code that we have to "patch" later, like removing warnings, removing checks, supporting dynamic pthread count while not allowing spawning new threads, etc. Also, for some reason, WASM initialization with pthreads takes longer (in our setup, it took about 1s to spawn 8 workers), whereas WASM Workers are faster, and we can easily work around this in our case.
    Most other benefits stem from our architecture, which better aligns with workers' ideology: an independent, limited, controlled number of workers who wait and perform isolated tasks.
    So nothing bad about pthreads (but JS size), it's just that we don't utilize the power of them.

    As for the bug, I gave it a try with a busy loop per guard (it's very rare, unless in certain scenarios). See #26283

    In our scenario, we are trying to "warm up" thread variables to avoid memory "pins" later; otherwise, we end up in fragmentation hell.

  7. sbc100 commented on Feb 17, 2026

    @sbc100
    Collaborator

    Thanks. So it sounds like there are a few issues stopping you from just switching to the pthreads:

    1. JS size (this sounds like something we can monitor and work on)
    2. You had to patch the generated JS code when using pthreads. This sounds bad and I would love to hear more about the specifics. Perhaps opening bug if you have time?
    3. Worker startup time was slower with threads. This is little surprising to me. I would have though the fixed costs of starting a new WebWorker and loading the program into it (which both wasm workers and pthreads fundamentally have to do) would dwarf any other types of startup cost (e.g. TLS init). We should measure this too and try to improve.
  8. sbc100 commented on Feb 19, 2026

    @sbc100
    Collaborator

    I'm also curious if we could make find a way to catch this kind of mistake (i.e. that accidental usage of pthread_locks from wasm workers). Its seems like a think that could bite us over and over again.

  9. AndreyRepko commented on Feb 22, 2026

    @AndreyRepko
    Author

    I have discussed it a bit with the team, and we think that at the current stage of our project, we will not switch to pthreads.
    As for the open bug for patching, I'm not sure it makes sense for everyone. Like, we are using tests for our JS code that run on Node, but we don't want to add special Node support in JS, since our aim is browsers and Node is just a test runner, so we disable Node detection. Then we have introduced the dispose method to unsubscribe from some events and do some cleanup (not sure if it's still needed in the recent versions of Emscripten), then we have "optimize" the heap-growing code, to elleminate not needed calls in a single JS function (like AsciiToString), we are also adding numbers to web-workers, so they are named em-ww-1, em-ww-2, then it's easier to distinguish them in devtools etc.

  10. sbc100 commented on Feb 22, 2026

    @sbc100
    Collaborator

    Thanks for pointing out that we don't include the ID in the name of wasm workers. Fix for that is in #26320

  11. sbc100 commented on Feb 24, 2026

    @sbc100
    Collaborator

    Now that the futex API is coming to Wasm Workers I think we can use that here: #26325

    However, I'm having trouble creating a test case that fails in the way you describe. In the OP you say that that pthread_cond_wait and then the thread goes into a busy loop.. but that doesn't sounds like it should leak to a deadlock or timeout. Or are you saying that somehow more than one thread can start initializing at once?

  12. juj commented on Feb 25, 2026

    @juj
    Collaborator

    Has it been considered implementing stubs (pthread_mutex_lock / pthread_cond_wait) for Wasm Workers, or is that the opposite of the idea of them?

    Yes, I think that is kind of exactly that opposite of idea of wasm workers. Pthread mutex's have a lot of complex modes of operation which I think is what @juj was trying to get away from with wasm workers.

    The never-ending challenge with any API function is that we want to ensure that it goes strict by "only-pay-for-what-you-use" philosophy (especially in APIs that aren't emulating native portability support). It warms me to hear you found Wasm Workers more lightweight in practice, so this has been panning out.

    In general, adding support for pthread_mutex_lock() and pthread_cond_wait() to Wasm Workers would be fine, as long as that only added to code size overhead to those Wasm Worker -targeting codebases that decided to call these pthread functions. But the challenge is that many of the pthread APIs require low platform startup level abstractions to be prepared at page load time, to help implement these APIs. So it easily ends up being a "need to add startup overhead scaffolding to enable pthread_mutex_lock() in Wasm Workers" situation, where every user would see a larger code size in the Wasm Workers API as result.

    It would be possible to implement a partial version of pthread_mutex_lock() that would avoid some of the API contracts that POSIX states (cancellation points, recursive locking come to mind), but it is not completely clear if that would be more confusing than worth; since it would not be the 100% exact thing.

  13. sbc100 commented on Feb 25, 2026

    @sbc100
    Collaborator

    I'm uploading #26336 which will turn this into a link time failure for now.

    Obviously we still hope to find a fix, but failing at build time seems like a better failure more for now.

  14. added a commit that references this issue on Feb 26, 2026
    c01004b
  15. reopened this on Feb 26, 2026
  16. changed the title [-]`__cxa_guard_acquire` busy-spins in WASM Workers leads to dead-lock[/-] [+]`__cxa_guard_acquire` does not work WASM Workers (depends on pthread functions)[/+] on Feb 26, 2026
  17. sbc100 commented on Feb 26, 2026

    @sbc100
    Collaborator

    I re-titled the issue to reflect the new reality now that #26336 landed.

    I think the solution we should aim for (using emscripten_futex API instead of pthread API) has not changed, its just easier to write a test now since i added a failing test in #26336.

  18. added 2 commits that reference this issue on Feb 26, 2026
    9de906d
    e7ad19c
  19. added a commit that references this issue on Feb 26, 2026
    dcf2f84
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    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