Multi-process exec

Node is built on the V8 engine, the model is similar to the browser, js will run on a single thread of a single process.

  • Benefits: The program state is single, there is no lock and thread synchronization problems in the case of multi-threading, and the operating system can improve the efficiency of the cpu due to less context switching during scheduling;
  • Disadvantages:
    1. Now the CPUs are all multi-core, and a Node process can only use one core -> How to make full use of the multi-core cpu server?
    2. Once the exception thrown on a single thread is not caught, it will cause the entire process to crash. How to ensure the robustness and stability of the process.

Multi-process architecture

1.child_process module: supports Node's ability to create child processes at will.
2. exec: spawn a shell and execute the command in the shell, and buffer any generated output, there is a callback function to know the status of the child process

index1.js

console.log('进程:' + process.argv[2] + "执行")

main1.js

const child_process = require('child_process');
for(var i = 0;i<3;i++){
    
      //循环开启3个线程
	var workerProcess = child_process.exec('node index1,js' + i,function(err,stdout,stderr){
    
      //开启一个新进程,执行Node index1文件,err是命令行的错误,stdout输出参数,stderr是执行的错误
	if(err){
    
    
		console.log(err) //命令行错误
	}else{
    
    
		console.log('stdout:',stdout)
		console.log('stderr:',stderr) //输出的错误
	}
	})

	workerProcess.on('exit',function(code){
    
    
		console.log('子进程已退出,退出码:'+code)
	})
}
  1. spawn spawns a new process using the command line parameters in the given command and args
const child_process = require('child_process');
for(var i = 0; i<3;i++){
    
    
	// stdout子进程输出结果
	// stderr子进程输出错误
	var workerProcess = child_process.spawn('node',['index1.js'],i)
	workerProcess.stdout.on('data',function(data){
    
    
		console.log('data:'+data)
	})
	workerProcess.stderr.on('data',function(data){
    
    
		console.log('err:'+data)
	})
	workerProcess.on('close',function(code){
    
    
		console.log('子进程已退出,退出码'+ code)
	})
}
  1. Fork derives new nodejs processes, each process has its own memory and uses its own V8 instance
const child_process = require('child_process');
for(var i = 0; i<3;i++){
    
    
	// stdout子进程输出结果
	// stderr子进程输出错误
	var workerProcess = child_process.fork('node',['index1.js'],[i])
	
	workerProcess.on('close',function(code){
    
    
		console.log('子进程已退出,退出码:'+ code)
	})
}

Guess you like

Origin blog.csdn.net/sinat_33940108/article/details/112886341