Repository navigation
Description
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:
libcxxabiis compiled without_LIBCXXABI_HAS_NO_THREADS(becauseis_ww=Trueinsystem_libs.py:1753), so__cxa_guard_acquireuses theGlobalMuteximplementation that callspthread_mutex_lock()/pthread_cond_wait()- But
libclinkslibrary_pthread_stub.c(becauseis_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
Use futex-based __cxa_guard for WASM Workers
sbc100 commentedon Feb 16, 2026
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
PlatformFutexWaitimplementation 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?
AndreyRepko commentedon Feb 16, 2026
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?
sbc100 commentedon Feb 16, 2026
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.
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.
[libcxxabi] Use InitByteFutex for __cxa_guard in WASM Workers
AndreyRepko commentedon Feb 17, 2026
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.
sbc100 commentedon Feb 17, 2026
Thanks. So it sounds like there are a few issues stopping you from just switching to the pthreads:
sbc100 commentedon Feb 19, 2026
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.
AndreyRepko commentedon Feb 22, 2026
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.
Include Wasm Worker ID in name of the worker in debug builds.
sbc100 commentedon Feb 22, 2026
Thanks for pointing out that we don't include the ID in the name of wasm workers. Fix for that is in #26320
Include Wasm Worker ID in name of the worker in debug builds.
Include Wasm Worker ID in name of the worker in debug builds. (#26320)
sbc100 commentedon Feb 24, 2026
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_waitand 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?juj commentedon Feb 25, 2026
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.sbc100 commentedon Feb 25, 2026
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.
[WASM_WORKERS] Don't define pthread function in WASM_WORKERS builds (#…
[-]`__cxa_guard_acquire` busy-spins in WASM Workers leads to dead-lock[/-][+]`__cxa_guard_acquire` does not work WASM Workers (depends on pthread functions)[/+]sbc100 commentedon Feb 26, 2026
I re-titled the issue to reflect the new reality now that #26336 landed.
I think the solution we should aim for (using
emscripten_futexAPI instead of pthread API) has not changed, its just easier to write a test now since i added a failing test in #26336.Build libc++abi with _LIBCXXABI_USE_FUTEX and emscripten futex API
Build libc++abi with _LIBCXXABI_USE_FUTEX and emscripten futex API
Build libc++abi with _LIBCXXABI_USE_FUTEX and emscripten futex API (e…