Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new worker thread.
Node.js
const { Worker } = require('worker_threads');
const worker = new [1]('./worker.js'); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Thread' or 'Process' instead of 'Worker'.
Trying to create a worker without importing the Worker class.
✗ Incorrect
In Node.js, the Worker class from the worker_threads module is used to create a new worker thread.
2fill in blank
mediumComplete the code to send a message from the main thread to the worker.
Node.js
worker.[1]('start');
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' or 'emit' which are not methods of Worker.
Trying to use 'write' which is for streams.
✗ Incorrect
The postMessage method sends a message to the worker thread.
3fill in blank
hardFix the error in the worker code to listen for messages.
Node.js
const { parentPort } = require('worker_threads');
parentPort.[1]('message', (msg) => {
console.log('Received:', msg);
}); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'listen' or 'handle' which are not valid methods.
Using 'addListener' which works but is less common than 'on'.
✗ Incorrect
The on method is used to listen for events like 'message' on parentPort.
4fill in blank
hardFill both blanks to create a pool of 4 workers and store them in an array.
Node.js
const workers = Array.from({ length: 4 }, () => new [1]('./worker.js')); // Create 4 workers workers.forEach(worker => worker.[2]('ready'));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Thread' instead of 'Worker'.
Using 'send' instead of 'postMessage'.
✗ Incorrect
Use Worker to create new worker threads and postMessage to send messages to them.
5fill in blank
hardFill all three blanks to handle worker exit events and restart the worker.
Node.js
workers.forEach((worker, index) => {
worker.on('exit', (code) => {
if (code !== 0) {
console.log(`Worker ${index} exited with code ${code}. Restarting...`);
workers[[1]] = new [2]('./worker.js');
workers[[3]].postMessage('start');
}
});
}); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Thread' instead of 'Worker'.
Using different variables for the first and third blanks.
✗ Incorrect
Use the index to replace the exited worker, create a new Worker, and send it a 'start' message.