Bird
0
0

How can you safely increment a shared counter in Node.js worker threads using SharedArrayBuffer and Atomics?

hard📝 Application Q8 of 15
Node.js - Worker Threads
How can you safely increment a shared counter in Node.js worker threads using SharedArrayBuffer and Atomics?
AUse <code>Atomics.add(sharedArray, 0, 1)</code> to increment the counter atomically.
BDirectly increment the value with <code>sharedArray[0]++</code> without synchronization.
CCreate a new <code>SharedArrayBuffer</code> for each increment operation.
DUse <code>setTimeout</code> to delay increments and avoid race conditions.
Step-by-Step Solution
Solution:
  1. Step 1: Understand Atomic Operations

    To avoid race conditions, increments must be atomic.
  2. Step 2: Use Atomics API

    Atomics.add performs atomic addition safely across threads.
  3. Step 3: Avoid Non-Atomic Operations

    Direct increments like sharedArray[0]++ are not atomic and can cause race conditions.
  4. Final Answer:

    Use Atomics.add(sharedArray, 0, 1) to increment the counter atomically. -> Option A
  5. Quick Check:

    Atomics ensure safe concurrent increments [OK]
Quick Trick: Always use Atomics for shared counter increments [OK]
Common Mistakes:
  • Incrementing without Atomics causing race conditions
  • Creating new buffers instead of sharing
  • Using timers to avoid synchronization issues

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes