수색…


소개

Node.js는 단일 스레드로 설계되었습니다. 모든 실제적인 목적을 위해 Node로 시작하는 응용 프로그램은 단일 스레드에서 실행됩니다.

그러나 Node.js 자체는 멀티 스레드로 실행됩니다. I / O 조작 등은 스레드 풀에서 실행됩니다. 또한 노드 응용 프로그램의 모든 인스턴스가 다른 스레드에서 실행되므로 다중 스레드 응용 프로그램을 실행하면 여러 인스턴스가 실행됩니다.

비고

이벤트 루프 를 이해하는 것은 여러 스레드를 사용하는 방법과 이유를 이해하는 것이 중요합니다.

클러스터

cluster 모듈을 사용하면 동일한 응용 프로그램을 여러 번 시작할 수 있습니다.

클러스터링은 서로 다른 인스턴스가 동일한 실행 흐름을 가지며 서로 의존하지 않는 경우에 바람직합니다. 이 시나리오에서는 포크와 포크 (또는 자식)를 시작할 수있는 마스터가 하나 있습니다. 아이들은 독립적으로 일하며 Ram과 Event Loop의 한 공간을 가지고 있습니다.

클러스터 설정은 웹 사이트 / API에 유용 할 수 있습니다. 모든 스레드는 다른 스레드에 종속되지 않으므로 모든 고객을 지원할 수 있습니다. 변수를 공유 할 수 없으므로 데이터베이스 (예 : Redis)가 쿠키를 공유하는 데 사용됩니다 ! 스레드간에.

// runs in each instance
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

console.log('I am always called');

if (cluster.isMaster) {
    // runs only once (within the master);
    console.log('I am the master, launching workers!');
    for(var i = 0; i < numCPUs; i++) cluster.fork();

} else {
    // runs in each fork
    console.log('I am a fork!');
  
    // here one could start, as an example, a web server
  
}

console.log('I am always called as well');

자녀 과정

Child Processes는 다른 초기화 및 우려 사항을 가지고 독립적으로 프로세스를 실행하고자 할 때 사용할 수있는 방법입니다. 클러스터의 포크처럼, child_process 는 스레드에서 실행되지만 포크와 달리 부모와 통신하는 방법이 있습니다.

의사 소통은 양방향으로 진행되므로 부모와 자녀는 메시지를 청취하고 메시지를 보낼 수 있습니다.

부모 (../parent.js)

var child_process = require('child_process');
console.log('[Parent]', 'initalize');

var child1 = child_process.fork(__dirname + '/child');
child1.on('message', function(msg) { 
    console.log('[Parent]', 'Answer from child: ', msg); 
});

// one can send as many messages as one want
child1.send('Hello'); // Hello to you too :)
child1.send('Hello'); // Hello to you too :)

// one can also have multiple children
var child2 = child_process.fork(__dirname + '/child');

하위 (../child.js)

// here would one initialize this child
// this will be executed only once
console.log('[Child]', 'initalize');

// here one listens for new tasks from the parent
process.on('message', function(messageFromParent) {
    
    //do some intense work here
    console.log('[Child]', 'Child doing some intense work');

    if(messageFromParent == 'Hello') process.send('Hello to you too :)');
    else process.send('what?');
    
})

메시지 옆에 '오류', '연결됨'또는 '연결 끊김'과 같은 여러 가지 이벤트를 들을 수 있습니다.

자식 프로세스를 시작하는 데는 특정 비용이 관련되어 있습니다. 하나는 가능한 한 적은 수의 스폰하기를 원할 것입니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow