Skip to content

Instantly share code, notes, and snippets.

@preveen-stack
Last active May 10, 2024 09:27
Show Gist options
  • Save preveen-stack/1d86216c040cffb61190e076a175bdc1 to your computer and use it in GitHub Desktop.
Save preveen-stack/1d86216c040cffb61190e076a175bdc1 to your computer and use it in GitHub Desktop.
SharedArrayBuffer in nodejs

SharedArrayBuffer is a feature in JavaScript that allows multiple JavaScript processes to share the same memory space. This can be particularly useful in scenarios where you need to communicate and synchronize data between different threads or processes efficiently.

In Node.js, SharedArrayBuffer is supported starting from version 12. It provides a way to share raw binary data across different JavaScript contexts, such as web workers, or in the case of Node.js, across different worker threads using the worker_threads module.

Here's a basic overview of how you can use SharedArrayBuffer in Node.js:

  1. Creating a SharedArrayBuffer: You can create a SharedArrayBuffer using the new SharedArrayBuffer() constructor. For example:

    const sab = new SharedArrayBuffer(1024); // Creates a SharedArrayBuffer with 1024 bytes
  2. Using SharedArrayBuffer with Worker Threads: In Node.js, you can use the worker_threads module to create and communicate with worker threads. You can pass a SharedArrayBuffer instance to a worker thread and perform operations on it from both the main thread and the worker thread. For example:

    const { Worker } = require('worker_threads');
    
    const sab = new SharedArrayBuffer(1024);
    
    const worker = new Worker('./worker.js', { workerData: sab });
    
    // In the worker.js file
    const { workerData } = require('worker_threads');
    
    // Now you can use workerData as a SharedArrayBuffer
  3. Synchronization: Since SharedArrayBuffer allows multiple threads to access and modify the same memory space concurrently, you need to use synchronization mechanisms like Atomics to coordinate access and avoid race conditions. Atomics provides atomic operations like add, sub, and, or, etc., which ensure that memory operations are performed atomically. For example:

    // Inside a worker thread
    const { Atomics } = require('worker_threads');
    
    // Add 1 to the value stored at index 0 of the SharedArrayBuffer atomically
    Atomics.add(sharedArrayBuffer, 0, 1);

It's important to note that SharedArrayBuffer is subject to security restrictions in web browsers due to its potential for abuse in creating Spectre-like attacks. As a result, some browsers have disabled or restricted its usage in unprivileged contexts. However, in Node.js, where you have more control over the execution environment, SharedArrayBuffer can be safely used within worker threads.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment