Gustav
Gustav

Reputation: 1341

How does node "actually" handle threads?

I read a lot about node js trying to understand the event loop and its patterns / anti patterns. One thing that many authors fail to mentions that node actually handles threads. The application programmer however doesn't get access to them of course, but it's nice to know that they exist and when they will kick in.

As far as I understand, when Ryan Dahl explains it, threads will be used only for file system access and networking. Thereby: not for computing... And my concern here is: why not computing?

Even if I place a looong for loop in a callback function it will block the entire loop when executed. Due to this image found on http://www.slideshare.net/cacois/nodejs-patterns-for-discerning-developers all registered callbacks will be handled by the advanced threading mechanism of node. But apparently not :(

enter image description here

Even if a lot of speed is gained from making io and file handling async, why not go the whole mile and make all the registered callbacks be handled by node's internal threads?

It just struck me though, that the shared concurrency wouldn't work with separate threads trying to access the global app namespace. (This might be a big reason)

What do you think?

Upvotes: 3

Views: 469

Answers (1)

Ry-
Ry-

Reputation: 225272

Even if a lot of speed is gained from making io and file handling async, why not go the whole mile and make all the registered callbacks be handled by node's internal threads?

That would break one of the fundamental “nice things” about Node.js. If you have this:

if (a === 7) {
    console.log(a);
}

a is guaranteed to be 7 when calling console.log, because it’s synchronous code. Parallel execution of synchronous code kind of breaks that. Sure, you can make an arbitrary break at callbacks and turn them into threads, but that’s no better than every other threading system.

There’s also the matter of threads being able to exhaust a system’s resources in a way a task queue can do only with great difficulty.

Upvotes: 4

Related Questions