emscripten-core / emscripten-core/emscripten

[Multithreading] PROXY_TO_PTHREAD & MAIN_THREAD_EM_ASM causes perf degradation

Open
#22,570 16 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

Please include the following in your bug report:

**Version of emscripten/emsdk:**
```
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.56 (cf90417346b78455089e64eb909d71d091ecc055)
clang version 19.0.0git (https:/github.com/llvm/llvm-project 34ba90745fa55777436a2429a51a3799c83c6d4c)
Target: wasm32-unknown-emscripten
Thread model: posix
InstalledDir: ~/emsdk/upstream/bin
```

I am trying to port my application from single-threaded to multi-threaded environment. I cannot ensure max number of threads required at a time by my application, thus I finalized using `PROXY_TO_PTHREAD`. In single-threaded mode, my application used to work like below:
1. C++ `main` function does some initialization. After `main` function exits, we keep the runtime alive.
2. We have exposed a C++ function to process events coming from the UI.

To port this architecture into multi-threaded environment I used `PROXY_TO_PTHREAD` to create a proxied main thread and kept that thread alive for further processing. I used [proxying](https://emscripten.org/docs/api_reference/proxying.h.html) to proxy events coming from UI to this detached thread. Once done, this thread called `MAIN_THREAD_EM_ASM` to send the response back to the main application thread. Also, this is the only `MAIN_THREAD_EM_ASM` that the detached thread does. Rest is C++ execution without waiting on anything else.

Functionality wise, this model worked well. But when doing performance analysis I figured out that I had a degradation of around 200-400 ms. Upon profiling, I could see that detached thread completed work in time but was waiting for around 200-400 ms for the `MAIN_THREAD_EM_ASM` to complete i.e. for main application thread to receive the response. Also, the main application thread was completey idle around this time. This can be seen in the below screenshot.

![Untitled design (1)](https://github.com/user-attachments/assets/d07e97c5-b536-4430-b2a4-463dcca75f30)


Is this performance degradation expected? Is there any other way I could model my app to get away with this? How can I minimise the time taken by the detached thread to send back the response?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.