node. js mechanism and Principle understanding preliminary

Source: Internet
Author: User

http://blog.csdn.net/leftfist/article/details/41891407

I. node. JS Pros and cons

node. js is a single thread.

The advantage is

1) Simple

2) High performance, avoids frequent thread switching overhead

3) Small footprint, because it is single-threaded, in the case of heavy load, the memory footprint is still very low

3) thread safety, no locking, unlock, deadlock these issues

Php

node. js

The downside is

How to solve high concurrency?

Node uses asynchronous IO and event-driven (callback functions) to solve this problem.

In general, a high concurrency solution provides a multithreaded model that provides a thread for each business logic to compensate for the time overhead of synchronous I/O calls through system thread switching. Like Apache, is a request for a thread.

node. JS uses a single-threaded model, with asynchronous requests for all I/O, avoids frequent context switching, maintains an event queue when node. JS executes, and waits for the next event to arrive at execution time, each asynchronous i/ o When the request is complete, it is pushed to the event queue for execution.

For example:

For a simple database access operation, this is done in the traditional way

[JavaScript]View PlainCopy 
    1. res = db.query (' SELECT * from some_table ');
    2. Res.output ();

When the code executes to the first line, the thread blocks, waits for query to return the result, and then continues processing. Due to database queries, disk reads and writes, network traffic, and so on (so-called I/O), blocking time can be very large (relative to CPU always frequency). For high-concurrency access, on the one hand, long-term blocking waits on the one hand, and the addition of new threads in order to cope with the new situation, wastes a lot of system resources, and the increase in threads also consumes a lot of CPU time to handle memory context switching. See how node. js Handles

[JavaScript]View Plaincopy < param name= "wmode" value= "Transparent" >
    1. Db.query (' SELECT * from some_table ', function (res) {
    2. Res.output ();
    3. });

The second argument to query is a callback function that executes to db.query without waiting for the result to return, but proceeds directly to the following statement until it enters the event loop. When the database execution results are returned, the event is sent to the event queue, and the previous callback function is not invoked until the thread enters the event loop.

The asynchronous mechanism of node. JS is event-based, and all I/O, network traffic, database queries are executed in a non-blocking manner, and the returned results are handled by the event loop. node. JS handles only one event at a time and enters the event loop to check for subsequent events as soon as it finishes. This allows the CPU and memory to concentrate on one thing at the same time, while simultaneously executing the time-consuming I/O operations in parallel.

Event Loop mechanism

The so-called event loop means that node. JS uses the event mechanism to resolve all asynchronous operations, and a thread is constantly looping through the event queue.

All of the logic in node. JS is the callback function for the event, so node. js is always in the event loop, and the program entry is the callback function for the first event in the event loop. An I/O request or a direct emission (emit) event may be issued in the callback function of the event, and the event loop is returned after execution is complete. The event loop checks that there are no unhandled events in the event queue until the program finishes. node. js's event loop is not visible to developers, implemented by the Libev library, and Libev constantly checks to see if there are active, detectable event listeners that exit the event loop until they are checked, and the program ends.

LIBUV is a high-performance event-driven library that encapsulates some of the underlying features of the Windows and Unix platforms, providing a unified API for developers.
Therefore, node. JS is single-threaded, asynchronous, non-blocking.

But after all, how to compensate for single-threaded defects? Is there an asynchronous non-blocking that you can rest easy on?

No.

1) CPU-intensive tasks exist short board

As mentioned above, the NODEJS mechanism is single threaded, inside this thread, there is an event loop mechanism that handles all requests: During the event processing, it will intelligently put some time-consuming operations, such as IO, network communication, to the worker threads to execute, and then callback, this is called asynchronous IO non-blocking bar. However, those non-IO operations, only CPU-based operations, it is carried out by itself, such as what the Fibonacci sequence. It is single-threaded, these self-carrying tasks to one after another to complete, the front of the unfinished, the back can only wait. As a result, more CPU-intensive tasks are required for higher CPU requirements, which can lead to high performance and slow response for highly concurrent node. JS servers.

2) Unable to take advantage of multi-core CPU

At the very beginning, a thread is simply a mechanism for assigning a single processor processing time. But if the operating system itself supports multiple cpu/cores, then each thread can get a different cpu/kernel for real "parallel operations". In this case, multithreaded programs can improve the efficiency of resource use. node. JS is a single-threaded thread that has only one event loop and consumes only one cpu/kernel. Most servers are now multi-CPU or multicore, and when the node. JS program's event loop is occupied by CPU-intensive tasks, causing other tasks to be blocked, there is still a cpu/kernel idle state, resulting in a waste of resources.

Solution Solutions

Use native modules or third-party modules to open up processes or sub-processes to handle these special tasks.

3) If there is an exception thrown because it is a single thread, the entire project will be unavailable. But this is the final question of code, bad code, no matter what the system, there will be problems, even if not crash. The solution is to run with tools like PM2?

Second, the relationship between Nodejs and JavaScript

Nodejs itself is not a development language, it is a tool or platform, in the server-side interpretation, Operation Javascript;coffeescript belongs to the Nodejs system, is a new development language, but its purpose is to finally compile into JavaScript.

Nodejs uses Google V8 to explain running JavaScript, but the code that the system actually executes is written in C + +. JavaScript does just call these APIs. Therefore, there is no question of the efficiency of implementation.

Three, Nodejs applicable scene

1. RESTful API

This is ideal for Node, because you can build it to handle tens of thousands of connections. It still does not require a lot of logic; it essentially simply looks up some values from a database and makes them a response. Because the response is small text, inbound requests are also small amounts of text, so traffic is not high, and a machine can even handle the API needs of the busiest companies.

2. Real-time program

such as Chat Service

The chat application is the best example of the advantages of node. JS: Lightweight, high-traffic, and good for running-intensive data on cross-platform devices (albeit with low computational power). At the same time, chatting is a very worthwhile use case because it is simple and covers most of the solutions that a typical node. js will use so far.

3. Single page app

Ajax is a lot. Now the single-page mechanism seems to be very popular, such as PhoneGap made out of the app, a page fit all examples abound.

。。。

In summary, Nodejs is suitable for scenarios where high concurrency, I/o intensive, and small business logic are used



Reference articles

A misunderstanding about node. js

node. JS Threads and processes

http://www.slideshare.net/mysqlops/nodejs-9313477

node. js weaknesses CPU Intensive tasks

Http://www.ruanyifeng.com/blog/2014/10/event-loop.html

http://segmentfault.com/a/1190000000375619

Http://www.cnblogs.com/sysuys/p/3460614.html

node. js mechanism and Principle understanding preliminary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.