Node Js Worker threads
Hello everyone 👋,
Worker threads help us to perform heavy synchronous operations without blocking the main thread.
We should not be doing the I/O operations in workers because Nodejs's main threads handle I/O operations better than workers.
The golden rule: don’t block the event loop, try to keep it running it and pay attention and avoid anything that could block the thread like synchronous network calls or infinite loops.
Let's take a look at the example:
In the above code in the route "/" getPi() is a method that loop on 10000000000. This roughly takes around 60 seconds to complete the request.
Since this is a synchronous operation it would be blocking the main thread execution and all the other requests will not be served.
To test it out, run the above code and hit "/" first and then "/hello". We would see that the second request will not be completed until the first request is completed.
To overcome this kind of situation we need to use worker threads where we will offload the blocking operation to the worker thread and once it is processed we will send the response back to the client.
So here we are spawning a worker thread here and sending a message to the worker thread to fetch the pi value. Once the value is returned from the worker we are sending the response back to the client.
This way we will not be blocking the main thread and other requests can be still processed as the worker thread execute in its separate event loop.
In case you want to play around code is available in github.
Please like and share if you find this interesting.