How does node.js implement non-blocking I/O?

风格不统一 提交于 2019-12-07 01:03:21

问题


From here i have found that node.js implements non-blocking i/o model. But i don't understand how.

As javascript is single threaded. How can a single thread do i/o operations and simultaneously executing the further process.


回答1:


It is true that operations such as sleep will be blocking the thread. But I/O events can indeed be asynchronous.

Node.js uses an event loop for this. An event loop is “an entity that handles and processes external events and converts them into callback invocations”

Whenever data is needed nodejs registers a callback and sends the operation to this event loop. Whenever the data is available the callback is called.

http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/ for more info




回答2:


The I/O that is handled by node.js is multithreaded internally.

It is the programming interface that is single threaded and asynchronous.




回答3:


Ryan Dahl: Original Node.js presentation at JSConf 2009 (Ryan is the creator of Node.js)

This video will answer your question.

The essence of JavaScript(v8) is event callbacks (button onclick="functions()" etc). That's how the I/O is multithreaded. We still have to write our code to not have blocking I/O by only writing callbacks; otherwise the code will wait on db.query responses and be blocking before executing the next line of code.



来源:https://stackoverflow.com/questions/18333432/how-does-node-js-implement-non-blocking-i-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!