Worker thread in node js
A Complete Guide to Worker threads in Node.js
If you are a developer you probably know is an asynchronous single thread language but in the background it uses multithreading. However, it is quite problematic to do complex CPU intensive operations.
Workers are a way to execute code asynchronously on a separate thread and create a message channel between them. Worker thread introduced in Node v10.x in an experimental flag (–experimental-worker) and stable in Node v12.x.
You can’t load the worker thread module in Node without the experimental-worker flag.
C:\Users\worker thread> node –experimental-worker -e “require(‘worker_threads’); console.log(‘success’);” Success
Worker threads are helpful for complex CPU intensive tasks and not for I/O tasks.
Working with single thread asynchronous Node.js
Some modules like cluster and child_process help to do this task. However, none of these arrangements was generally embraced because of the execution limit.
Let see the example
SetTimeout method takes time to execute but the “running in loop” message is displayed immediately. Node.js simply invokes the function but doesn’t block the execution of different bits of code. It will get notified through the callback when the question is done, and we will get the outcome. It will report when the task is completed.
What happens when we are required to do simultaneous extreme stuff? For example, performing complex estimations in memory in a huge dataset. In this situation, the event loop gets blocked and others need to wait until the task is not completed. Let’s consider the following example.
As you see, the function foo() is executed for loop up to 100000000 times. The main thread will be occupied with this task and it will ignore other client requests. To solve this problem we use worker thread.
Working of Worker Thread
Worker thread serves for performing CPU intensive problems. Worker thread provides an approach that builds multiple environments running on independent threads. Worker thread helps solve the problem of blockage of the event loop.
Let’s check the implementation of the worker thread from the following example.
run() function call runWorker() function to execute worker thread. We pass string as workerData through runWorker() function. We define worker constructor inside runWorker(). This constructor works as a thread. We pass two parameters in this worker constructor one is the filename and the other is options.
- Filename: The path of main worker script. The path of this file should be relative or full path.
- env-Environment variable
Some are event of worker threads
- message: worker thread invoke parentPort.postMessage() and data will be accessible in message event
- exit: whenever process.exit() method call worker will stop.
- error: worker thread throws an uncaught exception and in this situation worker thread terminates its process.
- online:worker thread has started execution js code
This file is boosted by worker thread as we already defined in the worker constructor. worker.js file is parent execution of worker thread. In worker.js file, there are two main parts – workerData and parentPort. Worker data access the data from the thread and parent port will be a message port enabling communication with the parent thread. To send data from parent to worker, postMessage() method is used. This will send to the message event in the main thread.
Some properties of worker thread
- isMainThread: True if it has a master process else false.
- WorkerData: Used to fetch data form worker constructor.
- parentPort: Its message port instance that turns into the best approach to communicate with parent thread.
- ThreadId: Identification of thread and it is given for every thread.
With worker thread, we can accomplish a much more productive application without making a halt circumstance. This is the way you can import the worker thread in an application and carry out the thread. With the proper thread support, we can foresee more engineers and developers from domains like AI, machine learning, and big data begin using Node.js.