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.
#include <cstdio>
#include <emscripten.h>
#include <thread>
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
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.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:Interestingly, it was working with some older versions (at least I checked
3.1.15
).