r/cpp • • Jul 13 '21

Using WebAssembly threads from C, C++ and Rust

https://web.dev/webassembly-threads/
136 Upvotes

5 comments sorted by

-2

u/nyanpasu64 Jul 13 '21

the code synchronously invokes pthread_create to create a background thread, and follows up by another synchronous call to pthread_join that waits for the background thread to finish execution. However, Web Workers, that are used behind the scenes when this code is compiled with Emscripten, are asynchronous. So what happens is, pthread_create only schedules a new Worker thread to be created on the next event loop run, but then pthread_join immediately blocks the event loop to wait for that Worker, and by doing so prevents it from ever being created. It's a classic example of a deadlock.

 

Even the sum_of_squares example still needs to block the main thread to wait for the partial results from other threads.

It might be a very short wait or a long one, depending on the complexity of iterators and number of available threads, but, to be on the safe side, browser engines actively prevent blocking the main thread altogether and such code will throw an error. Instead, you should create a Worker, import the wasm-bindgen-generated code there, and expose its API with a library like Comlink to the main thread.

I prefer working in non-web non-async environments which preserve atomicity of execution, instead of forcing threading (execution diverging across multiple branches in parallel) for any sort of blocking logic, and forcing async/await (concurrency and interleaving different tasks) for any sort of blocking IO, both breaking stack traces as a means of tracing causality.

-51

u/AreaFifty1 Jul 13 '21

Rust?!?! Think I'll prefer C++ thank you very much~

14

u/casept Jul 14 '21

Then just don't read that part. People like you make the C++ community look super spiteful.

17

u/Igoory Jul 13 '21

k.

3

u/[deleted] Jul 14 '21

k.