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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access