diff --git a/system/lib/pthread/proxying.c b/system/lib/pthread/proxying.c index f18c4d156bad7..7625eba8ab3a6 100644 --- a/system/lib/pthread/proxying.c +++ b/system/lib/pthread/proxying.c @@ -339,8 +339,11 @@ void emscripten_proxy_finish(em_proxying_ctx* ctx) { pthread_mutex_lock(&ctx->sync.mutex); ctx->sync.state = DONE; remove_active_ctx(ctx); - pthread_mutex_unlock(&ctx->sync.mutex); + // Signal must come before unlock to avoid emscripten_proxy_sync_with ctx + // seeing the state as DONE and freeing the ctx before we call unlock. + // See https://github.com/emscripten-core/emscripten/pull/26582 pthread_cond_signal(&ctx->sync.cond); + pthread_mutex_unlock(&ctx->sync.mutex); } else { // Schedule the callback on the caller thread. If the caller thread has // already died or dies before the callback is executed, then at least make @@ -365,8 +368,9 @@ static void cancel_ctx(void* arg) { if (ctx->kind == SYNC) { pthread_mutex_lock(&ctx->sync.mutex); ctx->sync.state = CANCELED; - pthread_mutex_unlock(&ctx->sync.mutex); + // Signal must be first, see comment in emscripten_proxy_finish. pthread_cond_signal(&ctx->sync.cond); + pthread_mutex_unlock(&ctx->sync.mutex); } else { if (ctx->cb.cancel == NULL || !do_proxy(ctx->cb.queue, diff --git a/test/codesize/test_codesize_minimal_pthreads.json b/test/codesize/test_codesize_minimal_pthreads.json index 75383a2ac05a7..0357f3034a021 100644 --- a/test/codesize/test_codesize_minimal_pthreads.json +++ b/test/codesize/test_codesize_minimal_pthreads.json @@ -2,9 +2,9 @@ "a.out.js": 7363, "a.out.js.gz": 3604, "a.out.nodebug.wasm": 19046, - "a.out.nodebug.wasm.gz": 8822, + "a.out.nodebug.wasm.gz": 8821, "total": 26409, - "total_gz": 12426, + "total_gz": 12425, "sent": [ "a (memory)", "b (exit)", diff --git a/test/codesize/test_codesize_minimal_pthreads_memgrowth.json b/test/codesize/test_codesize_minimal_pthreads_memgrowth.json index 4d941efd39106..cc47a8f9585d0 100644 --- a/test/codesize/test_codesize_minimal_pthreads_memgrowth.json +++ b/test/codesize/test_codesize_minimal_pthreads_memgrowth.json @@ -2,9 +2,9 @@ "a.out.js": 7765, "a.out.js.gz": 3810, "a.out.nodebug.wasm": 19047, - "a.out.nodebug.wasm.gz": 8823, + "a.out.nodebug.wasm.gz": 8822, "total": 26812, - "total_gz": 12633, + "total_gz": 12632, "sent": [ "a (memory)", "b (exit)",