emscripten-core / emsdk

Emscripten SDK
http://emscripten.org
Other
2.96k stars 676 forks source link

Unable to overwrite worker's onmessage when using MODULARIZE #1276

Closed miloszmaki closed 11 months ago

miloszmaki commented 11 months ago

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

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).

miloszmaki commented 11 months ago

Not sure if I posted this issue in the right place, moved to https://github.com/emscripten-core/emscripten/issues/20192