TIL. 프로세스와 스레드

const_yang·2022년 2월 9일
0

TIL

목록 보기
12/14
post-thumbnail

프로세스

  • 실행 파일, 애플리케이션을 실행하는 상태를 프로세스라고 한다.
  • 운영체제가 여러 프로세스를 함께 진행하기 때문에 멀티 태스킹이 가능하게 되었다.
  • 프로세스는 각각 독립된 메모리 영역(Code, Data, Stack, Heap의 구조)을 할당받는다.
  • 스레드는 프로세스 내에서 각각 Stack만 따로 할당받고 Code, Data, Heap 영역은 공유한다.

멀티 태스킹

멀티 태스킹이 가능하려면 프로세스의 동시성 (Concurrency)와 병렬성 (Parallelism) 특징을 각각 사용하거나, 혼합해서 사용해야 한다.

동시성 (Concurrency)

  • 하나의 Core에서 Context-Switch를 이용하여 동시에 여러 작업을 하는 것
  • Context-Switch: 다른 태스크(프로세스, 스레드)가 시작할 수 있도록 이미 실행 중인 태스크(프로세스, 스레드)를 멈추는 것

병렬성 (Parallelism)

  • 여러 Core에서 여러 스레드가 동시에 작업을 하는 것!

멀티 스레드

  • 스레드? 작업의 갈래
  • 멀티스레드? 하나의 프로세스 내에서 여러 작업 갈래로 나눠진 것

각 스레드마다 call stack이 존재하지만, 여러 스레드는 하나의 자원을 공유한다. 반면 프로세스는 프로세스마다 자원이 모두 다르다.
여러 스레드가 하나의 자원에 손을 대면 오류가 발생하게 된다. 이것이 멀티 스레드의 단점이다.

Node.js는 싱글 스레드로만 작동하는가?

node.js의 Event loop는 싱글 스레드로 작동되지만, Worker pool은 멀티 스레드로 작동한다.
즉, node.js의 초기화와 callback은 Event loop라는 하나의 프로세스, 하나의 스레드에서 작동되지만 I/O intensive, CPU intensive한 모듈은 Worker pool에서 작동한다.

How Node.js really works
Node.js uses two kinds of threads: a main thread handled by event loop and several auxiliary threads in the worker pool.
Event loop is the mechanism that takes callbacks (functions) and registers them to be executed at some point in the future. It operates in the same thread as the proper JavaScript code. When a JavaScript operation blocks the thread, the event loop is blocked as well.
Worker pool is an execution model that spawns and handles separate threads, which then synchronously perform the task and return the result to the event loop. The event loop then executes the provided callback with said result.
In short, it takes care of asynchronous I/O operations — primarily, interactions with the system’s disk and network. It is mainly used by modules such as fs (I/O-heavy) or crypto (CPU-heavy). Worker pool is implemented in libuv, which results in a slight delay whenever Node needs to communicate internally between JavaScript and C++, but this is hardly noticeable. (https://blog.logrocket.com/a-complete-guide-to-threads-in-node-js-4fa3898fe74f/)

0개의 댓글