Analysis on how to optimize the CPU-intensive calculation of node.js

Source: Internet
Author: User

First look at the code below

settimeout (function () {
for (var i = 0; i < 10000000000; i++) {
CPU Intensive
}
}, 200);
settimeout (function () {
Console.log (' 210 ms ... ');
}, 210);

This small example is a classic explanation of the Node.js encountered a dense CPU when the problem, the program is triggered at two points, although the callback in the 210MS when the program executes very quickly, but in 200ms when processing a very intensive CPU task will cause the entire thread blocked.
As for the event loop mechanism, you can refer to:
Http://www.infoq.com/cn/articles/nodejs-weakness-cpu-intensive-tasks
The passage in this article about event loop and tick:

The main thread of each node program has an event Loop,javascript code that runs all the way through this single thread. All I/O operations and calls to the local API are either asynchronous (with the help of the program's platform) or run on another thread. It's all handled through LIBUV. So when there's data on the socket, or when the local API function returns, there's a kind of synchronous way to invoke the JavaScript function that's interested in this particular event that just happened.

It is not safe to call the JS function directly in the thread where the event occurs, because it also encounters problems with conventional multithreaded procedures, race conditions, memory access to non-atomic operations, and so on. So to put events in a queue in a thread-safe way, if written in code, this should be roughly the case:

Lock (Queue) {
Queue.push (event);
}

Then execute JavaScript's mainline thread (the C code of event loop):

while (true) {
Tick start
Lock (Queue) {
var tickevents = copy (queue);
The thread that copies the entries in the current queue has its own memory
Queue.empty (); // .. Empty a Shared Queue
}
for (var i = 0; i < tickevents.length; i++) {
Invokejsfunction (Tickevents[i]);
}
Tick End
}

while (true) (not true in the real node source code, this is just for illustration) represents the event loop. The for is called the JS function for each event in the queue. The event loop invokes 0 or more callback functions associated with an external event in each tick, and tick ends once the queue is emptied and the last function returns. Then go back to the start (next tick) and start checking the events that other threads add to the queue while the JavaScript is running.

So who put everything in this queue?

Process.nexttick
Settimeout/setinterval
I/O (from FS, net, etc.)
CPU-intensive functions in crypto, such as crypto streams, PBKDF2, and PRNG
All local modules that use the LIBUV Task Force column to invoke the C + + library asynchronously

Similarly, the following code can also cause T2 interfaces to slow when the T1 interface is invoked.

App.get ("/t1", function* (next) {
for (var i=0; i<5000000000; i++) {
CPU-Intensive
}
Console.log ("T1");
});
App.get ("/t2", function* (next) {
Console.log ("T2");
});

So see Node.js is capable of CPU-intensive operations, of course, the answer is no, node.js although it is single-threaded, but can open multiple Node.js instances to take full advantage of multi-core, in addition Node.js also support subprocess, through the subprocess to calculate ...

For.js

var calc = function () {
for (var i = 0; i < 10000000000; i++) {
}
}
Process.on (' message ', function (m) {
Receive Message from primary thread
Console.log ("recv mesage");
Calc ();
Process.send (1);
});
Process.on (' Sighup ', function () {
Process.exit ()//Receive kill information, process exits
});

Main.js

var fork = require (' child_process '). Fork;
settimeout (function () {
var worker = fork ("./for.js");
Worker.on ("Message", function (m) {
Receive the results of a worker process
Console.log ("World");
Worker.kill ();
});
Worker.send (1);
}, 200);
settimeout (function () {
Console.log (' Hello ');
}, 210);

The above program is to use interprocess communication, For.js is a child process execution of intensive computing. Main.js can continue to schedule other programs. Make the most of the CPU.

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.