Worker Thread in NodeJs – Brain Mentors Skip to content

Worker Thread in NodeJs

Worker Thread in NodeJs

The Basic idea behind worker thread is to do cpu intensive work without blocking the main thread.

As we know that node js run on a single thread (event loop) hence using it for some highly cpu centric job would not be a good idea.

As it will increase the request processing time.

And user/clients of the applications will get the result in more time.

Now having a worker thread would look something like the below diagram.

Now unused part of cpu will have a thread running onto them and without mingling with the main thread execution and a code piece can be executed.

Lets start with the main.js program(below).

Here, a main thread will start to execute the code when we will run this particular file i.e., main.js.

IsMainthread will return either true or false based on who is executing the if condition.

So right now main thread is executing so if(isMainthread) will return true.

Now inside the if condition we can create a worker thread using Worker class of nodejs.

Here we have to pass the name of the file which the thread will start executing once it is created.

Eventually there could be a need to pass data from parent process which can be sent using workerData property of the thread class.

worker.threadId return the id of the newly created thread.

It is represented by simple numbers.

And now the possibility is that after the worker thread will complete its task it may want to send the result back to the main process.

For that purpose we can attach some events.

The events could be for message or exit and a callback can be attached to these events.



Now in the child process if we want to send message after completing the task been assigned to the worker, we have to use parentPort.

parentPort.postMessage(“here comes the message”);

will actually send the events message to the parent process hence the callback attached to that particular event will be executed.


Sign Up and Start Learning