Chapter 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 different options for using threads in a browser with relation to WebAssembly modules.

Definition

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 (see https://en.wikipedia.org/wiki/POSIX_Threads).

By default, a web page’s UI and JavaScript all operate in a single thread. If your code does too much processing without periodically yielding to the UI, the UI can become unresponsive. Your animations will freeze, and the controls on the web page won’t respond to a user’s input, which can be frustrating for the user.

If the web page remains unresponsive for long enough (typically around 10 seconds), a browser might even prompt the user to see if they want to stop the page, as figure 9.1 shows. If a user stops the script on your web page, the page may no longer function as expected unless the user refreshes it.

Tip

To keep web pages as responsive as possible, whenever you interact with a Web API that has both synchronous and asynchronous functions, it’s a best practice to use the asynchronous functions.

9.1. Benefits of web workers

9.2. Considerations for using web workers

9.3. Prefetching a WebAssembly module using a web worker

9.4. Using pthreads

Real-world use cases

Exercises

Summary

sitemap