Chapter 7. WebAssembly
While the title of this book is Multithreaded JavaScript, modern JavaScript runtimes also support WebAssembly. For the unaware, WebAssembly (often abbreviated as WASM) is a binary-encoded instruction format that runs on a stack-based virtual machine. It’s designed with security in mind and runs in a sandbox where the only things it has access to are memory and functions provided by the host environment. The main motivation behind having such a thing in browsers and other JavaScript runtimes is to run the parts of your program that are performance-sensitive in an environment where execution can happen much faster than JavaScript. Another goal is to provide a compile target for typically compiled languages like C, C++, and Rust. This opens the door for developers of those languages to develop for the web.
Generally, the memory used by WebAssembly modules is represented by ArrayBuffers
, but it can also be represented by SharedArrayBuffers
. In addition, there are WebAssembly instructions for atomic operations, similar to the Atomics
object we have in JavaScript. With SharedArrayBuffers
, atomic operations, and web workers (or worker_threads
in Node.js), we have enough to do the full suite of multithreaded programming tasks using WebAssembly.
Before we jump into multithreaded WebAssembly, let’s build a “Hello, World!” example and execute it, to find the strengths and limitations of WebAssembly.
Your First WebAssembly
While WebAssembly is a binary format, a plain ...
Get Multithreaded Javascript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.