Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

OT but can someone explain this?

PHP: Starts reading from database, blocks everything else, returns data.

Node: Starts reading from database, lets it go and continues with other stuff until the data is ready and then returns it.

I understand it in theory but since Node is single-threaded, doesn't it need to use that thread for the database operations? Which means it's blocking the program until it's done anyway?



I believe what happens is it registers the functions callback on the event-loop which it'll check the next time around to see if it's done, then pushes the work to be handled in a separate pool of threads that libuv manages. When it's done, the next event-loop tick or the next time around it will execute the callback with the results. This is how asynchronous functions work anyways, but some functions are actually synchronous functions such as JSON.stringify, so if you are doing a JSON.stringify on a huge JSON object, you're literally grinding everything to a halt until you're done doing that


Thanks. So Node is actually using multiple threads behind the scenes or did I read that wrong? How do I know which kind of operations are pushed there by libuv?


Yeah, there's a pool of non-blocking C++ threads that do the work behind the scenes. Any async operation gets pushed out, and honestly most functions will behave asynchronously. JSON parsing is a sync operation that usually doesn't block for very long because it will be a small operation 99.9% of the time, so it's kind of a pitfall because you almost never see this blocking issue unless your parsing huge JSON objects. In nodeland things are kind of expected to be asynchronous, and if they are not they should be labeled as such so that everyone using it knows. Checkout the FileSystem (fs) nodejs lib, you'll see calls explicitly labeled as "sync" to denote that they are blocking.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: