FrontendDeveloper.in

ECMAScript question detail

Shared memory and atomics

The Atomics is a global object which provides atomic operations to be performed as static methods. They are used with SharedArrayBuffer(fixed-length binary data buffer) objects. The main use cases of these methods are,

  1. atomic operations: When memory is shared, multiple threads can read and write the same data in memory. So there would be a chance of loss of data. But atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted.

It provides static methods such as add, or, and, xor, load, store, isLockFree etc as demonstrated below.

const sharedMemory = new SharedArrayBuffer(1024);
const sharedArray = new Uint8Array(sharedMemory);
sharedArray[0] = 10;

Atomics.add(sharedArray, 0, 20);
console.log(Atomics.load(sharedArray, 0)); // 30

Atomics.sub(sharedArray, 0, 10);
console.log(Atomics.load(sharedArray, 0)); // 20

Atomics.and(sharedArray, 0, 5);
console.log(Atomics.load(sharedArray, 0));  // 4

Atomics.or(sharedArray, 0, 1);
console.log(Atomics.load(sharedArray, 0));  // 5

Atomics.xor(sharedArray, 0, 1);
console.log(Atomics.load(sharedArray, 0)); // 4

Atomics.store(sharedArray, 0, 10); // 10

Atomics.compareExchange(sharedArray, 0, 5, 10);
console.log(Atomics.load(sharedArray, 0)); // 10

Atomics.exchange(sharedArray, 0, 10);
console.log(Atomics.load(sharedArray, 0)); //10

Atomics.isLockFree(1); // true
  1. waiting to be notified: Both wait() and notify() methods provides ways for waiting until a certain condition becomes true and are typically used as blocking constructs.

Let's demonstrate this functionality with reading and writing threads.

First define a shared memory and array

const sharedMemory = new SharedArrayBuffer(1024);
const sharedArray = new Int32Array(sharedMemory);

A reading thread is sleeping and waiting on location 0 which is expected to be 10. You can observe a different value after the value overwritten by a writing thread.

Atomics.wait(sharedArray, 0, 10);
console.log(sharedArray[0]); // 100

Now a writing thread stores a new value(e.g, 100) and notifies the waiting thread,

Atomics.store(sharedArray, 0, 100);
Atomics.notify(sharedArray, 0, 1);
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399