First of all, the advantages of Nodejs single thread:
High Performance , avoiding the overhead of frequently creating switching threads, faster execution, and less resource usage than PHP.
thread safety , do not worry about the same variable is multithreaded read and write, causing the program crashes.
single-threaded asynchronous and non-blocking , in fact, nodejs the underlying access I/O or multi-threaded, blocking/non-blocking and asynchronous/synchronous is two different concepts, synchronization does not mean blocking, but the blocking is definitely synchronous; a bit around, please listen to my example, I went to the cafeteria to eat, I chose a package, Then the staff helped me to the food, if I stood beside, waiting for the staff to give me a meal, this is called synchronization; if the staff help me to eat, the people who are behind me start ordering, so that the whole canteen service is not because I am waiting for a package to stop, this situation is called non-blocking. This example simply illustrates synchronous but non-blocking situations. If I am waiting for food to buy drinks, and so on to hear the call and then go back to get the package, at this time my drink has been bought, so I wait for food and also carry out the task of buying drinks, the call is equal to the implementation of the callback, is asynchronous non-blocking. If I'm buying a drink, I've already called my number to get the package, but I've waited a long time to get the drink, so I may have to call my meal number in the lobby long after I get a package, which is a single-threaded blocking situation.
Multithreading:
A thread is a basic unit of CPU scheduling, and a CPU can perform only one thread task.
Nodejs can also perform multi-stroke tasks, such as referencing the TAGG/TAGG2 module, you can look at my previous article, there are specific ways to use. However, whether tagg/tagg2 are using the Pthread Library and V8::isolate class to achieve the JS multithreading function, according to the rules we execute in the thread of the function can not use the core API Nodejs, such as Fs,crypto module, so there is a great limitation.
Multi-process:
In a browser that supports HTML5, we can use Webworker to throw some time-consuming computations into the worker process so that the main process does not block and the user does not feel the lag.
Here we need to take advantage of the Nodejs child_process module,child_process provides a fork method, you can start a Nodejs file, as a worker process, worker After the work is done, the result is sent to the main process, and then the worker exits automatically, so that we can use the multi-process to solve the problem of the main thread blocking.
var express = require (' Express '); var fork = require (' child_process '). Fork;var app = Express (); App.get ('/', function (req, RES) { var worker = fork ('./work.js ')//Create a worker process worker.on (' message ', function (m) {//Receive worker process evaluates if (' Object ' = = = typeof m && m.type = = = ' Fibo ') { worker.kill ();//Send signal to kill process Res.send (m.result.tostring ()); /Return the result to the client } }); Worker.send ({type: ' Fibo ', NUM:~~REQ.QUERY.N | | 1}); Number of Fibo to be sent to the worker process}); App.listen (7878);
We listen to the 7878 port through Express, the request to each user will fork a child process, by calling the Worker.send method to pass the parameter n to the child process, while listening to the message of the child process sent messages event, the result response to the client.
The following is the fork work.js file content:
var Fibo = function Fibo (n) {//definition algorithm return n > 1? Fibo (n-1) + Fibo (n-2): 1;} Process.on (' message ', function (m) {//Receive the message sent over by the main process if (typeof m = = = ' object ' && m.type = = = ' Fibo ') { var num = Fibo (~~m.num); Calculate Jibo process.send ({type: ' Fibo ', result:num}) //Calculate complete return result });p Rocess.on (' SIGHUP ', function () { process.exit ();//Receive Kill message, process exit});
We first define the function Fibo to compute the Fibonacci array, then listen to the message sent by the main thread, and send the result to the main thread after the calculation is complete . It also listens to the Sighup event of the process, triggering the event to exit.
Here we have a point to note that the main thread of the kill method does not really make the child process exit, but will trigger the Sighup event of the child process , the real exit or rely on process.exit ().
Summarize:
The fork method using the Child_process module does allow us to solve the problem of single-threaded blocking of CPU-intensive tasks without the limitation of the node. JS Core API that cannot be used with the Tagg package.
Single-threaded asynchronous node. JS does not mean that it does not block, too many tasks in the main thread can cause the main thread to die, affecting the performance of the entire program, so we have to be very careful to handle a large number of loops, string concatenation and floating point operations, such as CPU-intensive tasks, reasonable use of various techniques to throw the task to sub- E.js main thread is unblocked.
The use of threads/processes is not without overhead, minimizing the number of threads/processes created and destroyed, which can improve the overall performance of our system and the probability of errors.
Nodejs Intensive CPU Solution