chapter nine

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.

9.1   Benefits of web workers

9.2   Considerations for using web workers

9.3   Pre-fetch a WebAssembly module using a web worker

9.3.1   Adjusting the calculate primes logic

9.3.2   Use Emscripten to generate the WebAssembly files

9.3.3   Copying files to the correct location

9.3.4   Creating the HTML file for the webpage

9.3.5   Creating the JavaScript file for the webpage

9.3.6   Creating the web worker’s JavaScript file

9.3.7   Viewing the results

9.4   Using pthreads

9.4.1   Adjusting the calculate primes logic to create and use four pthreads

9.4.2   Using Emscripten to generate the WebAssembly files

9.4.3   Viewing the results

9.5   Exercises

9.6   Summary