Home > Article > Web Front-end > Detailed explanation of resource sharing between NodeJS parent process and child process
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('message', function(msg) { switch (msg) { case triggerEvent.inc: globalDataSuccess++; console.log('globalDataSuccess = ', globalDataSuccess); break; case triggerEvent.dec: globalDataSuccess--; console.log('globalDataSuccess = ', globalDataSuccess); break; } }); } console.log('Master globalDataError = ', globalDataError); } else { globalDataError++; console.log('Worker globalDataError = ', 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!