5 Reasons why Lisbon will crush it in 2018

After a few difficult years in an economic recession, Lisbon managed to re-invent itself as a hub for the arts and technology oriented startups, and is poised to enter 2018 with the rocket engines at…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




To be fair

Gottcha! 😱

If you were anything like me, you would’ve come here thinking:

But that’s only partially true! Bare with me.

Node.js’s Main Thread is indeed single threaded, simply because it’s plain JavaScript. There’s no other way.
This very thread is the one that’s executing all user written code (and the place where the Event Loop is doing its magic!)

Yet there are also a lot of moving parts of Node.js that aren’t necessarily single threaded.

Going from here we’re about to act on OS level and therefore we can of course leverage multi threading!
libuv is managing something that is called a “thread pool”.
Each of those threads in this pool can get assigned (by the event loop) a specific task from your Event Queue and work on it concurrently.

Alrighty, this one takes a bit less than a second to finish.
So, in a truly single threaded world this means if I call the “doExpensiveHasing” function 4 times it would take a total time of about 4 seconds (each one about one second), right?

Let’s see than.

Jup, you just saw multiple threads kicking in inside of a Node.js application.
To prove that it would be different if it actually executed on one thread only, we can change our environment variable:

As you can see we JavaScript developers have to be careful when claiming Node.js would be entirely single threaded because de facto it isn’t.
And this is actually a good thing.
Imagine having the power of asynchronous code but only executing it in a single thread.

Knowing this seems to be part of really understanding Node.js and hence writing performant code and leveraging its real powers.

Thank you for reading!
Please let me know if there is something unclear or wrong. 🤓

Add a comment

Related posts:

Discovering PERMACULTURE

I spent last week in Tenerife attending a training course about Permaculture, in the context of the European project PERMIND that I work in. It was a great opportunity to learn about the fascinating…

Iranians Hold Protest Rallies after Real Cause of Plane Crash Revealed

There was a protest gathering held by Amirkabir University of Technology students after the IRGC announced its air defence has unintentionally shot down the Ukrainian passenger plane, leaving all the…

Does the Earth Really Revolve and Rotate?

I know we put this matter to rest about a century ago, though after a lot of logical fallacies and complexity biases, but it is well in order to take a review on the matter. I am admittedly no one in…