Bird
0
0

// Shared buffer and typed array const sab = new SharedArrayBuffer(4); const counter = new Int32Array(sab); counter[0] = 0; // Increment function function increment() { // Which line correctly increments?

hard📝 state output Q15 of 15
Node.js - Worker Threads
You want to safely increment a shared counter in a Node.js worker thread using SharedArrayBuffer. Which code snippet correctly increments the counter without race conditions? // Shared buffer and typed array const sab = new SharedArrayBuffer(4); const counter = new Int32Array(sab); counter[0] = 0; // Increment function function increment() { // Which line correctly increments? }
AAtomics.add(counter, 0, 1);
Bcounter[0] = counter[0] + 1;
Ccounter[0] += 1;
Dcounter[0]++;
Step-by-Step Solution
Solution:
  1. Step 1: Understand race conditions in shared memory

    Directly modifying counter[0] with normal operators can cause race conditions when multiple threads run concurrently.
  2. Step 2: Use atomic operations for safe increments

    Atomics.add(counter, 0, 1) safely increments the value at index 0 without conflicts.
  3. Final Answer:

    Atomics.add(counter, 0, 1); -> Option A
  4. Quick Check:

    Use Atomics for safe shared memory updates [OK]
Quick Trick: Always use Atomics methods to update shared memory safely [OK]
Common Mistakes:
  • Using normal arithmetic on shared memory
  • Ignoring atomicity causing race conditions
  • Assuming ++ or += are thread-safe

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes