Home  >  Article  >  Web Front-end  >  Detailed explanation of resource sharing between NodeJS parent process and child process

Detailed explanation of resource sharing between NodeJS parent process and child process

小云云
小云云Original
2018-03-19 09:23:261986browse

This article mainly introduces the principle and implementation method of resource sharing between NodeJS parent process and child process, and analyzes the related operating techniques of nodejs based on the cluster module to realize resource sharing between parent process and child process in the form of examples. I hope it can help everyone.

Experimental goal: Realize resource sharing between parent process and child process

Using module: cluster

Introduction: Establish a node cluster to implement multiple processes, use child_process to implement IPC, solve multi-core utilization, and improve performance.

Principle:

1 Multi-process architecture of Master-worker master-slave mode

2 fork() Copy the process to make full use of CPU resources (determined by the number of cores)

3 Each process has its own area. If operations are performed in their respective areas, the resources are not shared. By listening to the message event and send, message passing is achieved to achieve the effect of resource sharing

4 globalDataError is the wrong resource sharing method, and globalDataSuccess is the correct resource sharing method.

Implementation code:


##

var cluster = require('cluster');
var cpus = require('os').cpus();
// 传递的事件名
var triggerEvent = {
    inc: 'inc',
    dec: 'dec'
}
// 错误的数据共享方式
var globalDataError = 0;
if (cluster.isMaster) {
  // 正确的数据共享方式
  var globalDataSuccess = 0;
  globalDataError++;
  // 启动多个进程,取决于内核数
  for (var i = 0; i < cpus.length; i++) {
    var worker = cluster.fork();
    worker.on(&#39;message&#39;, function(msg) {
      switch (msg) {
        case triggerEvent.inc:
          globalDataSuccess++;
          console.log(&#39;globalDataSuccess = &#39;, globalDataSuccess);
          break;
        case triggerEvent.dec:
          globalDataSuccess--;
          console.log(&#39;globalDataSuccess = &#39;, globalDataSuccess);
          break;
      }
    });
  }
  console.log(&#39;Master globalDataError = &#39;, globalDataError);
} else {
  globalDataError++;
  console.log(&#39;Worker globalDataError = &#39;, globalDataError);
  process.send(triggerEvent.dec);
  process.send(triggerEvent.inc);
}

The above is the detailed content of Detailed explanation of resource sharing between NodeJS parent process and child process. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn