emscripten-core / emscripten-core/emscripten
Unable to overwrite worker's onmessage when using MODULARIZE
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
Consider this example, which creates a new worker thread. The worker overwrites its `onmessage` to handle custom messages. Then the main thread sends a custom message to the worker.
```cpp
#include
#include
#include
int main() {
printf("hello from main\n");
std::thread t{[](){
EM_ASM({
console.log("hello from thread");
const def_onmsg = self.onmessage;
self.onmessage = (e) => {
console.log("handling message:", e, e.data, e.data.cmd);
if (e["data"]["cmd"] != "custom1" && e["data"]["cmd"] != "custom2") {
def_onmsg(e);
}
};
// self.onmessage({"data": {"cmd": "custom1", "id": 1}}); // this works always
});
}};
EM_ASM({
// setTimeout(()=>{ // doesn't help either
const threads = Module["PThread"].pthreads;
const id = Object.keys(threads)[0];
const worker = threads[id];
worker.postMessage({"cmd": "custom2", "id": 2}); // this fails with MODULARIZE
// },1000);
});
return 0;
}
```
It works properly ("custom2" message gets handled by the worker) when I build with:
`emcc main.cpp -o test.html --std=c++20 -pthread -s PTHREAD_POOL_SIZE_STRICT=0`
However, it stops working (the console prints error "worker.js received unknown command custom2") when I build with:
`emcc main.cpp -o test.html --std=c++20 -pthread -s PTHREAD_POOL_SIZE_STRICT=0 -s MODULARIZE=1 -s EXPORT_ES6=1`
My output of `emcc -v` is:
```
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.45 (ef3e4e3b044de98e1811546e0bc605c65d3412f4)
clang version 18.0.0 (https://github.com/llvm/llvm-project d1e685df45dc5944b43d2547d0138cd4a3ee4efe)
Target: wasm32-unknown-emscripten
Thread model: posix
```
Interestingly, it was working with some older versions (at least I checked `3.1.15`).
Contributor guide
Assessment
This issue has not been assessed yet.