Main thread creates worker and sends message correctly.
Step 2: Common worker.js mistake
Inside worker.js, parentPort must be imported to receive and send messages.
Final Answer:
Missing import of parentPort in worker.js -> Option B
Quick Check:
Worker needs parentPort import to communicate = C [OK]
Hint: Worker.js must import parentPort to handle messages [OK]
Common Mistakes:
Thinking postMessage is invalid on worker instance
Believing file path must be absolute always
Using 'onmessage' instead of 'message' event
5. You want to perform CPU-heavy calculations in a Node.js app without blocking the main thread. Which approach best uses worker threads to achieve this?
hard
A. Create a worker thread for each calculation and communicate results via messages.
B. Run all calculations in the main thread using async/await.
C. Use setTimeout to delay calculations in the main thread.
D. Spawn child processes instead of worker threads for parallelism.
Solution
Step 1: Understand CPU-heavy task impact
CPU-heavy tasks block the main thread if run there, freezing the app.
Step 2: Worker threads for parallelism
Creating worker threads for each calculation runs them in parallel without blocking the main thread, communicating results via messages.
Step 3: Evaluate other options
Async/await does not prevent blocking for CPU tasks; setTimeout only delays but does not parallelize; child processes are heavier and more complex than worker threads.
Final Answer:
Create a worker thread for each calculation and communicate results via messages. -> Option A
Quick Check:
Use worker threads for parallel CPU tasks = A [OK]
Hint: Use worker threads to run heavy tasks in parallel [OK]