How does concurrency work in nodejs?

I am trying to understand how concurrency works in a single threaded environment like nodejs.

Let's say I have this code:

var fs = require('fs');

fs.readFile('file1', function one(err, data) {
  // some code...
});

fs.readFile('/file2', function two(err, data) {
  // some code...
});

      

Now every call fs.readFile

is asynchronous. Thus, they work at the same time. But if all of this happens in a single thread, then how is concurrency achieved? Whether tags are performed function one

and function two

at the same or a different thread?

Basically how does node.js handle concurrency?

+3


source to share


3 answers


As far as Node is concerned, there is only one thread. Asynchronous calls are placed in the event queue and only fired on the next tick.

For code that Node migrates to C ++, all bets are off. There may or may not be streams. But that doesn't affect you.



The explanation that was most effective for me is "What the heck of an event loop anyway?" Philip Roberts , because the slow motion visualization tool he shows makes things pretty clear (for me, anyway).

You can experiment with the Philip Loupe tool online.

+4


source


Node.js uses multiple threads to handle skin io users, but this is hidden from the user. The application environment (i.e. your code) only has access to one thread, but Node.js transparently passes io to a separate thread without the need for a user.

In your case, function 1 and 2 are running on the same thread, but the actual io operations to read the file data are done on separate threads.



A more detailed description of the Node.js threading / io model can be found here and a good set of similar examples can be found here .

+3


source


The thing with node.js is that everything is done at the same time, except for your code.

So what this means is that there are actually many threads running inside the node.js VM (or thread pool if you like), and these threads are used when you call the async function, like o file operations, access databases, requesting urls, etc.

However, there is only one thread for your code, and it handles events from the event queue . So when you register the callback, this link is actually passed to the background worker thread, and as soon as the async operation is done, a new event is added to the event queue with this callback.

+2


source







All Articles