Nodejs solves the problem of how to share data among multiple processes in the cluster module, nodejscluster
Aforementioned
Nodejs added a cluster module after v0.6.x to implement multi-process. It uses the child_process module to create and manage processes and increase program performance on multi-core CPU machines. This article describes how to share data using the multi-thread created by the cluster module.
Data sharing between processes
The Code is as follows:
Var cluster = require ('cluster'); var data = 0; // data defined here is not shared by all processes. Each process has its own memory region 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, called numCPUs data ++; console. log ('data VALUE in ChildProcess % d: % d' cluster. worker. id, data );}
The running result is as follows:
Why shouldn't the variables declared outside the main process code block and sub-process code block be global variables? The answer is no. Because each process has its own region in the memory, the data ++ operation is performed in its own region, that is, the variable data is not shared. So how can we share data between processes? Let's 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 (); // listen to the message event worker_process.on ('message', function (msg) {if (msg. cmd & msg. cmd = 'policyrequest') {data ++; console. log ('data VALUE: % d', DATA) ;}} else {process. send ({cmd: 'policyrequest '});}
The running result is as follows:
Therefore, to share data, you need to use message notifications between processes.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.