mentioned earlier
Nodejs added a module cluster to implement multiple processes after v0.6.x, using child_process modules to create and manage processes, and to increase the performance of programs on multi-core CPU machines. This article describes the problem of how to share data with multithreading created using the cluster module.
Inter-process data sharing
Let's start with a simple example of the following code:
var cluster = require (' cluster ');
var data = 0;//Defines that data 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 {//subprocess, will be invoked Numcpus
data++;
Console.log (' Data VALUE in childprocess%d:%d ' cluster.worker.id, DATA);
}
The results of the operation are as follows:
Why should variables declared outside of the main process code block and the child Process code block not be global variables? The answer is in the negative. Because each process has its own area in memory, the data++ operation is performed in its own area, which means 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 processes Notifyrequest ') {
data++;
Console.log (' Data VALUE:%d ', data);}}
);
}
else {
process.send ({cmd: ' notifyrequest '});
}
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 goal.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.