Chapter 5. Advanced Shared Memory

Chapter 4 looked at using the SharedArrayBuffer object to read and write directly to a collection of shared data from across separate threads. But doing so is risky business, allowing one thread to clobber data that was written by another thread. However, thanks to the Atomics object, you are able to perform very basic operations with that data in a way that prevents data from being clobbered.

Although the basic operations provided by Atomics are convenient, you will often find yourself needing to perform more complex interactions with that data. For example, once you’ve serialized data as described in “Data Serialization”, like a 1 kilobyte string, you’ll then need to write that data to the SharedArrayBuffer instance, and none of the existing Atomics methods will allow you to set the entire value all at once.

This chapter covers additional functionality for coordinating reads and writes to shared data across threads for situations when the previously covered Atomics methods just aren’t enough.

Atomic Methods for Coordination

These methods are a little different than the ones that were already covered in “Atomic Methods for Data Manipulation”. Specificially, the methods previously covered each work with a TypedArray of any kind and may operate on both SharedArrayBuffer and ArrayBuffer instances. However, the methods listed here will only work with Int32Array and BigInt64Array instances, and they only make sense when used with SharedArrayBuffer ...

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.