<aside> 💡 노드에서 멀티 스레드 방식으로 작업할 수 있음

</aside>

노드에서는 멀티 스레드가 원래 안되던걸 할 수는 있게 해둔 것이다.

const {
  Worker, isMainThread, parentPort,
} = require('worker_threads');

if (isMainThread) { // 부모일 때
  const worker = new Worker(__filename); // 다른 파일도 가능하다는 것.
  worker.on('message', message => console.log('from worker', message));
  worker.on('exit', () => console.log('worker exit'));
  worker.postMessage('ping'); // 워커 하나 생성
} else { // 워커일 때
  parentPort.on('message', (value) => { // value로 값이 들어옴
    console.log('from parent', value);
    parentPort.postMessage('pong'); // 퐁으로 받는다.
    parentPort.close();
  });
}

특이하게 isMainThread로 분기처리 해줘야 한다.

메인일 경우냐, 워커스레드냐에 따라 두 가지로 나눠서 처리한다.

처음엔 메인이 실행되면서 거기서 워커를 실행하면서 일을 분배해주고 워커에서 일 마치면 메인으로 보내서 메인에서 합친다.

우리가 메인 스레드에서 일을 여러 개로 직접 프로그래밍해서 분배해주고 합쳐서 리턴해주는 것까지 해줘야 한다.

동시에 돌아가는 이점은 있다.

여러 워커를 만들어보자

if (isMainThread) { // 부모일 때
    const worker = new Worker(__filename); // 다른 파일도 가능하다는 것.
    const threads = new Set(); // 중복되지 않은 배열 -> Set()
    threads.add(new Worker(__filename, {
        workerData: {start : 1},
    }))
    threads.add(new Worker(__filename, {
        workerData: {start : 2},
    }))
    for (let worker of threads){
        worker.on('message', message => console.log('from worker', message));
        worker.on('exit', () => {
            threads.delete(worker);
            if (threads.size === 0){
                console.log('끝'); // 이렇게 직접 확인을 해줘야 한다.
            }
        });
    }