In this post I will show an example of how to use threading with WebAssembly.
Screenshot of the demo application below:
This data model is populated from user input in the spreadsheet, but this is unimportant for the WebAssembly side of things.
Please note, I am in no way a C++ expert, so I am always happy to receive suggestions for improvements here.
Next let’s look at the rest of the C++ application:
Here I am spawning 4 threads using the C++ threading api (pthread_create and pthread_join). The number of available threads has to be specified as a parameter to the compiler. In my case I am setting the thread pool size to 4, which means I can spawn a maximum of 4 threads.
In Emscripten you can specify the thread pool size and opt into threading by setting the flags USE_PTHREADS=1 and PTHREAD_POOL_SIZE=4
Running in the Browser
I should also point out that WebAssembly threading seems to have spotty browser support. So far I have only been able to run it in modern versions of Chrome.
The full source for this example is available on Github.