官术网_书友最值得收藏!

Node.js is single-threaded!

With the advent of the web, the traditional JavaScript was intended to add simple functionality and minimal runtime in the browser. Thus, JavaScript was kept as a single-threaded scripting language. Now, just to get a brief idea regarding single-threaded model, let's consider the following diagram:

A single-threaded model creates a single Callstack in an execution context. In the preceding code, when the function getData() is invoked, the function is pushed in the stack for execution sequentially.

In the context of Node.js, JavaScript is the base scripting language, hence, Node.js is single-threaded. You might be asking, how does a single-threaded model help? Typical PHP, ASP.NET, Ruby, or Java-based servers follow a model where each client request results in the instantiation of a new thread or even a process.

When it comes to Node.js, requests are run on the same thread with shared resources. A question that is often asked is, what will be the advantage of using such a model? To understand this, we should understand the problem that Node.js tries to resolve. It tries to do asynchronous processing on a single thread to provide more performance and scalability for applications that are supposed to handle too much web traffic. Imagine web applications that handle millions of concurrent requests; if the server makes a new thread for handling each request that comes in, it will consume a lot of resources and we will end up trying to add more and more servers to increase the scalability of the application.

The single-threaded, asynchronous processing model has its advantage in the previous context, and you can process much more concurrent requests with fewer server-side resources. However, there is a downside to this approach; Node (by default) will not utilize the number of CPU cores available on the server it is running on, without using extra modules like pm2.

The point that Node.js is single-threaded doesn't mean that it doesn't use threads internally. It is just that the developer and the execution context that the code has exposure to have no control over the threading model internally used by Node.js.
If you are new to the concept of threads and process, I would suggest you go through some preliminary articles about these topics. There are plenty of YouTube videos on the same topic as well.
The following reference could be used as a starting point:
http://www.cs.ucsb.edu/~rich/class/cs170/notes/IntroThreads/
主站蜘蛛池模板: 上栗县| 定襄县| 宽甸| 广饶县| 九龙坡区| 繁昌县| 平遥县| 丰台区| 扎囊县| 四子王旗| 慈利县| 中卫市| 凯里市| 聊城市| 锡林郭勒盟| 泰顺县| 且末县| 吉林省| 安新县| 盱眙县| 双流县| 内黄县| 清涧县| 集贤县| 皮山县| 扎鲁特旗| 阳西县| 镇雄县| 扎囊县| 石屏县| 汕头市| 青铜峡市| 静海县| 务川| 山阴县| 乌兰察布市| 黔东| 嘉峪关市| 柞水县| 礼泉县| 天等县|