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

查看:94
本文介绍了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 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天全站免登陆