Communication between Threads:
To facilitate communication between the main thread and worker threads, we utilize the `parentPort` object provided in the worker file specified within the Worker class. This allows worker threads to both send messages to and receive messages from the main thread:
Receiving Data in Worker Thread from Main Thread: Within the worker thread, we can listen to messages from the main thread using the `parentPort` as below. This allows the worker thread to act upon any data or instructions sent by the main thread.
Sending Data to Main Thread from Worker Thread: To send data or messages from the worker thread back to the main thread, we use `parentPort.postMessage`. This will dispatch the specified data back to the main thread.
In the main thread, when a message is sent from the `parentPort` in the worker.js file, we'll receive that message using the `worker.on ("message")` method. If something goes wrong in the worker thread and there's an unhandled error, the `worker.on ("error")` method will come into play. And when the worker thread finishes its job and exits, we can catch that event in `worker.on ("exit")`. It's like keeping an eye on what's happening in the worker thread from the main thread.
Terminating Worker Threads:
If we want to stop a worker thread when we're done with it, we’ll just use the `worker.terminate()` method. It's like turning off the lights when we leave a room.
Remember old tasks: By using tools like caching, Node.js doesn't have to redo tasks it's done before.