9 Threading: web workers and pthreads
This chapter covers:
- Using a web worker to fetch and compile a WebAssembly module
- Instantiating a WebAssembly module on behalf of Emscripten’s JavaScript code
- Creating a WebAssembly module that uses pthreads
In this chapter, you’re going to learn about the different options you have for using threads in a browser with relation to WebAssembly modules.
Info
A thread is a path of execution within a process, and a process can have multiple threads. A pthread, also known as a POSIX thread, is an API defined by the POSIX.1c standard for an execution module that’s independent of programming language: https://en.wikipedia.org/wiki/POSIX_Threads
By default, the UI and JavaScript of a webpage all operate in a single thread. If your code does too much processing without yielding to the UI periodically, it can cause the UI to become unresponsive. Your animations will freeze and the controls on the webpage won’t respond to a user’s input which can be very frustrating for a user.
If the webpage remains unresponsive for long enough (typically around 10 seconds), a browser may even prompt the user to see if they want to stop the page, as shown in figure 9.1. If the user stops the script on your webpage, your webpage may no longer function as expected unless the user refreshes it.
Figure 9.1 A long-running process has caused Firefox to become unresponsive. The browser is prompting the user to see if they want to terminate the script.