Is it really Node.js single-threaded? Threading in Node.js
In this blog, we will create a thread for CPU extensive tasks that not blocking the main event loop.
As we know, Node.js is a JavaScript runtime environment and runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser.
A Node.js app is run in a single process and JavaScript doesn’t support threading, then How we can do CPU extensive and long-running tasks without blocking the main event loop?
Is it really Node.js single-threaded?
Not really, Your JavaScript is not support threading but not Node.js, Node.js internally uses C++, recent addition of Node.js added support for
worker_threads
.
Each worker thread instance is really new instance of the event loop. Creating a new worker thread effectively gives a new event loop.
The following code demonstrates that, wasteTime()
function-blocking from executing other code.
Now we can fix this using worker threads, we will create worker thread for wasteTime()
.
You can see the right away that the main event loop not blocked this time. We immediately got output from the main thread. It’s time worker thread’s event loop blocked by wasteTime()
. After completing the processing worker thread passes a message to the main thread.
Note: Workers (threads) are useful for performing CPU-intensive JavaScript operations. They will not help much with I/O-intensive work. Node.js’s built-in asynchronous I/O operations are more efficient than Workers can be.
Contact : https://pprathameshmore.github.io/