node.js 如何工作? [英] How node.js works?

查看:25
本文介绍了node.js 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 nodejs 的一些事情不太了解.每个信息源都说 node.js 由于缺少线程锁定和上下文切换而比标准线程 Web 服务器更具可扩展性,但我想知道,如果 node.js 不使用线程,它如何并行处理并发请求?事件 I/O 模型是什么意思?

I don't understand several things about nodejs. Every information source says that node.js is more scalable than standard threaded web servers due to the lack of threads locking and context switching, but I wonder, if node.js doesn't use threads how does it handle concurrent requests in parallel? What does event I/O model means?

非常感谢您的帮助.谢谢

Your help is much appreciated. Thanks

推荐答案

Node 是完全事件驱动的.基本上,服务器由一个线程一个接一个地处理事件组成.

Node is completely event-driven. Basically the server consists of one thread processing one event after another.

传入的新请求是一种事件.服务器开始处理它,当有阻塞 IO 操作时,它不会等到它完成,而是注册一个回调函数.然后服务器立即开始处理另一个事件(可能是另一个请求).当 IO 操作完成时,这是另一种事件,服务器将在有时间时通过执行回调来处理它(即继续处理请求).

A new request coming in is one kind of event. The server starts processing it and when there is a blocking IO operation, it does not wait until it completes and instead registers a callback function. The server then immediately starts to process another event (maybe another request). When the IO operation is finished, that is another kind of event, and the server will process it (i.e. continue working on the request) by executing the callback as soon as it has time.

因此服务器永远不需要创建额外的线程或在线程之间切换,这意味着它的开销很小.如果要充分利用多个硬件核心,只需启动多个node.js实例

So the server never needs to create additional threads or switch between threads, which means it has very little overhead. If you want to make full use of multiple hardware cores, you just start multiple instances of node.js

更新在最低级别(C++ 代码,而不是 Javascript),实际上在node.js中有多个线程:有一个IO工作池,其工作是接收IO中断并将相应的事件放入队列中以供主线程处理.这样可以防止主线程被中断.

Update At the lowest level (C++ code, not Javascript), there actually are multiple threads in node.js: there is a pool of IO workers whose job it is to receive the IO interrupts and put the corresponding events into the queue to be processed by the main thread. This prevents the main thread from being interrupted.

这篇关于node.js 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆