3

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?

1
  • 1
    Watch this video: vimeo.com/96425312 Commented Jul 7, 2014 at 21:54

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, but there are SYNCronous disk and networking functions too. Asyncronous functions usually come with callbacks, so if I for example write something like this I would like it to execute the callback in another thread: setTimeout(function(){ for(...;..;..){ //loooong loop } }, 0);
@Gustav: As per my answer… no, you can’t, and that wouldn’t be good. The callback shares an execution environment with the code that called setTimeout, and could change its variables. Spawn a new process instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.