mentioned above
Nodejs added a module cluster after v0.6.x to implement multi-process, use the Child_process module to create and manage processes, and increase the performance of programs on multicore CPU machines. This article describes the issue of how multithreading can be shared with cluster modules.
inter-process data sharing
Let's start with a simple example with the following code:
var cluster = require (' cluster '); var data = 0;//Here the definition is not shared by all processes, each process has its own memory area if (Cluster.ismaster) {//main process var Numcpus = require (' OS '). CPUs (). length; For (var i = 0; i < Numcpus; i++) { var worker = Cluster.fork (); } data++; Console.log (' Data VALUE in mainprocess:%d ', data);} else {//Sub-process, will be called Numcpus times data++; Console.log (' Data VALUE in childprocess%d:%d ' cluster.worker.id, DATA);}
The results of the operation are as follows:
Why should we declare variables outside the main process code block and the child Process code block should not be global variables? The answer is in the negative. Because each process has its own area in memory, the data++ operation is performed within its own region, meaning that the variable data is not shared. So how do you share data between processes? Look at the following code:
var cluster = require (' cluster '); var http = require (' http '); if (cluster.ismaster) { var Numcpus = require (' OS '). CPUs (). length; var data = 0; Start multiple processes. for (var i = 0; i < Numcpus; i++) { //Add a process var worker_process = Cluster.fork (); Message Event worker_process.on (' message ', function (msg) { if (msg.cmd && msg.cmd = = ') Listening for child process Notifyrequest ') { data++; Console.log (' Data VALUE:%d ', DATA);}} ); } else {
The results of the operation are as follows:
Therefore, if you need to share data, you need to use message notifications between processes to achieve this purpose.
Turn from (http://www.cnblogs.com/CodeGuy/archive/2013/05/27/3101312.html)
Multi-process shared data problem of cluster module in Nodejs