Node.js Backend Development Bootcamp · درس

مشاركة الذاكرة باستخدام SharedArrayBuffer وAtomics

نسّق الخيوط عبر الذاكرة المشتركة باستخدام Atomics لتجنب نسخ المخازن المؤقتة الكبيرة ومنع حالات السباق

الدرس 3 من 413 خطوة

مشاركة الذاكرة باستخدام SharedArrayBuffer وAtomics درس مجاني في Node.js Backend Development Bootcamp على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Node.js Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Node.js Backend Development Bootcamp 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why Shared Memory?

When you spin up a Worker in Node.js and call postMessage, the data you send is copied using the structured clone algorithm. For small messages that is fine, but for a large numeric buffer (millions of bytes) copying wastes CPU and memory.

  • SharedArrayBuffer lets multiple threads read and write the same block of memory with zero copying.
  • Atomics gives you safe, race-free operations on that memory.

This lesson shows how to coordinate threads over shared memory in a CPU-bound backend job.

ArrayBuffer vs SharedArrayBuffer

An ArrayBuffer is owned by one thread. When transferred to a worker, the sender loses access to it. A SharedArrayBuffer (SAB) is different: passing it to a worker shares the same backing store, so both threads see each other's writes.

You never read raw bytes directly. Instead you wrap the buffer in a typed array view such as Int32Array or Float64Array.

const sab = new SharedArrayBuffer(16);
const view = new Int32Array(sab);

console.log(view.length);
view[0] = 42;
console.log(view[0]);
console.log(sab.byteLength);

Passing a SAB to a Worker

To share memory, create the SharedArrayBuffer in the main thread and send it via postMessage. Unlike a normal buffer, a SAB is shared (not transferred), so both sides keep using it.

The worker wraps the same SAB in its own typed array view. No copy happens.

const { Worker, isMainThread, workerData } = require('worker_threads');

if (isMainThread) {
  const sab = new SharedArrayBuffer(4);
  const view = new Int32Array(sab);
  view[0] = 100;
  new Worker(__filename, { workerData: sab });
} else {
  const view = new Int32Array(workerData);
  view[0] += 1;
  console.log('worker sees', view[0]);
}

The Race Condition Problem

Plain reads and writes on a shared view are not safe when multiple threads touch the same slot. A statement like view[0] += 1 is really three steps: read, add, write. Two threads can interleave and lose updates.

  • Thread A reads 5, Thread B reads 5.
  • Both compute 6 and write 6.
  • Two increments happened, but the value only went up by one.

This is a classic data race. The fix is Atomics.

Atomics.add for Safe Counters

Atomics.add(view, index, value) performs read-modify-write as a single indivisible operation. No other thread can interleave, so increments are never lost.

Other useful methods: Atomics.sub, Atomics.and, Atomics.or, and Atomics.load / Atomics.store for plain reads and writes that are guaranteed visible across threads.

const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);

Atomics.store(counter, 0, 0);
Atomics.add(counter, 0, 5);
Atomics.add(counter, 0, 3);

console.log(Atomics.load(counter, 0));

Splitting CPU Work Across Threads

Imagine summing a huge array of integers, a CPU-bound task that would block the event loop. With shared memory you store the data once and let several workers each process a slice, writing partial results into a shared output slot via Atomics.add.

Because the input lives in a SharedArrayBuffer, you never copy the dataset to each worker. They all read the same bytes.

Compare-and-Exchange

Atomics.compareExchange(view, index, expected, replacement) writes replacement only if the current value equals expected, and returns the value that was there. This is the building block for lock-free algorithms and simple spinlocks.

Use it to claim a slot exactly once: if the swap succeeds, this thread won the claim.

const sab = new SharedArrayBuffer(4);
const slot = new Int32Array(sab);
Atomics.store(slot, 0, 0);

const prev = Atomics.compareExchange(slot, 0, 0, 1);
console.log('previous value was', prev);
console.log('claimed:', prev === 0);

const again = Atomics.compareExchange(slot, 0, 0, 1);
console.log('second claim succeeded:', again === 0);

Blocking with Atomics.wait

Sometimes a worker must pause until another thread signals it. Atomics.wait(view, index, expectedValue) blocks the calling thread while the slot still holds expectedValue. It returns 'ok', 'not-equal', or 'timed-out'.

  • Atomics.wait only works off the main thread (it would freeze the event loop otherwise).
  • Atomics.notify(view, index, count) wakes waiting threads.

This gives you a true thread barrier without busy-looping.

Notify to Wake Workers

The producer thread updates the shared slot with Atomics.store and then calls Atomics.notify to wake any thread parked in Atomics.wait. The order matters: change the value first, then notify.

In a real backend job this is how a coordinator releases all workers at once to start a phase, or signals that input is ready.

const { Worker, isMainThread, workerData } = require('worker_threads');

if (isMainThread) {
  const sab = new SharedArrayBuffer(4);
  const signal = new Int32Array(sab);
  Atomics.store(signal, 0, 0);
  new Worker(__filename, { workerData: sab });
  setTimeout(() => {
    Atomics.store(signal, 0, 1);
    Atomics.notify(signal, 0, 1);
  }, 50);
} else {
  const signal = new Int32Array(workerData);
  Atomics.wait(signal, 0, 0);
  console.log('worker released, value =', Atomics.load(signal, 0));
}

A Complete Parallel Sum

Here is the full pattern in one runnable file: a shared input buffer, a shared result slot, and two workers that each sum half the data and atomically add their partial into the result. The main thread waits for both to finish.

Notice the input is never copied; both workers read the same SharedArrayBuffer.

const { Worker, isMainThread, workerData } = require('worker_threads');

if (isMainThread) {
  const N = 1000;
  const dataSab = new SharedArrayBuffer(N * 4);
  const data = new Int32Array(dataSab);
  for (let i = 0; i < N; i++) data[i] = i + 1;

  const resultSab = new SharedArrayBuffer(8);
  const result = new Int32Array(resultSab);
  Atomics.store(result, 0, 0);
  Atomics.store(result, 1, 0);

  let done = 0;
  const ranges = [[0, N / 2], [N / 2, N]];
  for (const [start, end] of ranges) {
    const w = new Worker(__filename, { workerData: { dataSab, resultSab, start, end } });
    w.on('exit', () => {
      if (++done === ranges.length) {
        console.log('total =', Atomics.load(result, 0));
      }
    });
  }
} else {
  const { dataSab, resultSab, start, end } = workerData;
  const data = new Int32Array(dataSab);
  const result = new Int32Array(resultSab);
  let local = 0;
  for (let i = start; i < end; i++) local += data[i];
  Atomics.add(result, 0, local);
}

Practical Cautions

Shared memory is powerful but easy to misuse. Keep these rules in mind:

  • SharedArrayBuffer only stores numbers. To share strings or objects you must encode them (for example with TextEncoder into a Uint8Array).
  • Always use Atomics for any slot more than one thread might write; mixing plain writes and atomic writes reintroduces races.
  • Reserve a fixed slot for synchronization flags and document its index.
  • Use shared memory only when copying is a real bottleneck; for most messages plain postMessage is simpler and safe.

Quick Check

You have several worker threads incrementing one shared counter stored in an Int32Array backed by a SharedArrayBuffer. Which approach keeps the count correct under concurrency?

Recap

You learned how to coordinate Node.js worker threads over shared memory:

  • SharedArrayBuffer shares one backing store across threads with no copying; wrap it in a typed array like Int32Array.
  • Plain += on a shared slot causes data races; use Atomics for any concurrently written slot.
  • Atomics.add, Atomics.load, Atomics.store, and Atomics.compareExchange give race-free reads, writes, and lock-free claims.
  • Atomics.wait (off the main thread) plus Atomics.notify let threads block and signal without busy-looping.
  • Reach for shared memory only when copying large numeric buffers is a real bottleneck.
البدء مجانًا

تعلم JavaScript مع معلم ذكاء اصطناعي — مجانًا

اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.

الدورات
22
الدروس
92

الأسئلة الشائعة

هل درس «مشاركة الذاكرة باستخدام SharedArrayBuffer وAtomics» مجاني؟

نعم — نص درس «مشاركة الذاكرة باستخدام SharedArrayBuffer وAtomics» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Node.js Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة Node.js Backend Development Bootcamp 4 دروس في المجموع.

ماذا ستتعلم في «مشاركة الذاكرة باستخدام SharedArrayBuffer وAtomics»؟

نسّق الخيوط عبر الذاكرة المشتركة باستخدام Atomics لتجنب نسخ المخازن المؤقتة الكبيرة ومنع حالات السباق تتمرن على Node.js Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Node.js Backend Development Bootcamp؟

لا تُشترط خبرة سابقة. Node.js Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «مشاركة الذاكرة باستخدام SharedArrayBuffer وAtomics»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Node.js Backend Development Bootcamp هذا؟

نعم. كل درس في Node.js Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. لماذا تتوقف حلقة الأحداث عند تنفيذ الأعمال المرتبطة بالمعالج
  2. إنشاء خيوط Worker وتمرير الرسائل
  3. مشاركة الذاكرة باستخدام SharedArrayBuffer وAtomics
  4. بناء تجمع Worker قابل لإعادة الاستخدام لزيادة معدل المعالجة
← العودة إلى Node.js Backend Development Bootcamp