2024. 11. 15. 23:12ㆍ정보처리,전산/NODEJS
이벤트 루프 (Event Loop)는 자바스크립트의 비동기 처리 모델에서 중요한 역할을 한다. 자바스크립트는 싱글 스레드 방식으로 동작하지만, 비동기적으로 여러 작업을 처리할 수 있도록 이벤트 루프를 통해 작업을 효율적으로 처리한다.
이벤트 루프의 주요 단계:
- Timers (타이머):
- setTimeout 또는 setInterval로 예약된 콜백 함수가 이 단계에서 실행된다. 타이머는 설정된 시간이 지나면 콜백이 실행되도록 한다.
-
setTimeout(() => { console.log('2초 후 실행'); }, 2000);
- Pending Callbacks (대기 중인 콜백):
- I/O 작업(예: 파일 읽기, 네트워크 요청)의 콜백이 이 단계에서 실행된다. 이전 단계에서 비동기적으로 처리된 I/O 작업이 완료되면, 해당 콜백 함수들이 이 단계에서 실행된다.
- 예: 파일을 읽은 후에 실행되는 콜백.
- Idle, Prepare (유휴, 준비):
- 이 단계는 Node.js 내부에서만 사용되는 단계로, 실제로 콜백을 실행하는 단계는 아니다. 주로 시스템 준비 작업을 처리한다.
- Poll (폴링):
- 이벤트 루프가 실제로 이벤트를 기다리는 단계이다. 이 단계에서는 I/O 이벤트나 네트워크 요청 등과 같은 이벤트를 기다리고, 이벤트가 발생하면 해당 콜백을 처리한다.
- 만약 대기 중인 이벤트가 없다면, 이벤트 루프는 여기서 대기한다.
- 예: HTTP 요청이나 파일 읽기 작업.
- Check (체크):
- setImmediate로 예약된 콜백이 이 단계에서 실행된다. setImmediate는 I/O 이벤트 후에 바로 실행되어야 하는 작업을 예약하는 데 사용된다.
setImmediate(() => { console.log('즉시 실행'); });
- setImmediate로 예약된 콜백이 이 단계에서 실행된다. setImmediate는 I/O 이벤트 후에 바로 실행되어야 하는 작업을 예약하는 데 사용된다.
- Close Callbacks (종료 콜백):
- 이 단계는 리소스를 정리하는 단계로, 서버 연결을 닫거나 파일 스트림을 닫는 등의 작업이 처리된다.
- 예: 서버 종료, 데이터베이스 연결 종료 등.
이벤트 루프 단계 요약:
1. Timers → setTimeout(), setInterval() 콜백 실행 (지연된 콜백)
2. Pending Callbacks → 비동기 I/O 작업 콜백 실행
3. Idle, Prepare → Node.js 내부 준비 작업 (콜백 실행 없음)
4. Poll → I/O 이벤트 대기 및 처리
5. Check → setImmediate() 콜백 실행
6. Close Callbacks → 리소스 종료 및 처리
// 타이머 콜백
setTimeout(() => {
console.log('타이머 콜백 실행!');
}, 1000);
// setImmediate 콜백
setImmediate(() => {
console.log('즉시 콜백 실행!');
});
// 비동기 파일 읽기 콜백 (대기 중인 콜백)
fs.readFile('file.txt', (err, data) => {
console.log('파일 읽기 완료!');
});
console.log('프로그램 실행 완료!');
실행 순서:
- setTimeout은 1초 후에 실행되므로 타이머 콜백 실행!이 출력된다.
- setImmediate는 I/O 이벤트가 처리된 후 바로 실행되므로, 즉시 콜백 실행!이 출력된다.
- fs.readFile은 비동기 작업이므로 I/O 이벤트 후에 파일 읽기 완료!가 출력된다.
- 프로그램 실행 완료!는 모든 비동기 작업 전에 출력된다. 이는 동기 코드가 먼저 실행되기 때문이다.
이벤트 루프의 역할:
- 이벤트 루프는 자바스크립트가 싱글 스레드 환경에서도 비동기적으로 여러 작업을 처리할 수 있도록 도와준다. 이를 통해 파일 읽기, 데이터베이스 접근, 네트워크 요청 등과 같은 I/O 작업을 효율적으로 처리하면서도, 메인 스레드는 다른 작업을 계속 처리할 수 있다.
- 각 단계에서 실행되는 콜백 함수들은 대기 중인 이벤트가 없으면 해당 대기열에 들어가며, 이벤트 루프가 계속해서 이를 처리한다.
요약:
- 타이머: setTimeout, setInterval의 콜백을 실행한다.
- 대기 중인 콜백: 비동기 I/O 작업의 콜백을 실행한다.
- 폴링: 이벤트가 도달할 때까지 기다리고, 도달하면 처리한다.
- 즉시 콜백: setImmediate를 사용해 즉시 실행되는 콜백을 처리한다.
- 종료 콜백: 리소스를 닫고 종료 작업을 수행한다.
The Event Loop is a core part of JavaScript's concurrency model, particularly in environments like Node.js, where non-blocking I/O operations are handled. It manages the execution of multiple operations without blocking the main thread, enabling JavaScript to perform asynchronous operations efficiently.
Here is an overview of how the Event Loop works, with key stages and queues like timers, poll, idle, and prepare:
Event Loop Structure Breakdown:
- Timers:
- setTimeout and setInterval callbacks are executed in this phase, but only after their specified delay has passed. The callbacks are not executed immediately; they wait until their timeout has expired.
- Pending Callbacks:
- This queue is responsible for executing the callbacks from I/O operations like reading files or network requests. These are callbacks that were scheduled in previous phases (e.g., I/O operations that need to be handled after completion).
- Example: Callbacks that are triggered after file read operations or database queries.
- Idle, Prepare:
- This is an internal phase used by Node.js to perform preparatory work before the poll phase. It doesn't involve executing user-defined callbacks directly but handles internal housekeeping tasks.
- Example: It's more about managing the internal state of the event loop and the environment.
- Poll:
- This is the phase where the event loop waits for incoming events or I/O operations. It checks for any I/O events (like network or database requests) and schedules them for execution if needed.
- If there are no events, the event loop will block here, waiting for I/O operations to complete.
- Example: If you're making an HTTP request or accessing a database, this is the phase where it waits for the response.
- Check:
- This phase runs after the poll phase and is typically used for executing callbacks scheduled by setImmediate(). This allows you to run code as soon as possible after the poll phase, but after I/O events have been processed.
- Close Callbacks:
- The last phase is responsible for handling the close events like closing a database connection or closing a socket. If there are any events registered for closing resources, they will be executed in this phase.
- Example: Closing a file stream or shutting down a server.
Event Loop Phases (Simplified):
- Timers Phase: Callbacks like setTimeout and setInterval are executed if their time limit is met.
- Pending Callbacks: Executes I/O callbacks, like callbacks from fs.readFile() or network responses.
- Poll Phase: The event loop waits for incoming events. If no events are available, it waits for new events, and if events are found, it processes them.
- Check Phase: setImmediate callbacks are executed here.
- Close Callbacks: If there are any close events like closing a server connection, they are handled in this phase.
- setTimeout callback will execute after 1 second (in the timers phase).
- setImmediate callback will execute immediately after the poll phase (usually after I/O callbacks).
- fs.readFile will schedule an I/O callback that gets executed after the I/O operation completes in the poll phase.
- The final log (Program execution complete!) will be printed before all the asynchronous tasks because the synchronous code always executes first.
In summary, the Event Loop ensures that JavaScript can perform asynchronous I/O operations without blocking the main execution thread, which is crucial for the efficient handling of tasks like file reading, database access, and network communication.
'정보처리,전산 > NODEJS' 카테고리의 다른 글
간단한 HTTP 서버를 만드는 기본적인 Node.js (0) | 2024.11.17 |
---|---|
이벤트 루프와 setImmediate 및 setTimeout의 실행 순서 (0) | 2024.11.15 |
HTML 내에서 메뉴 클릭 이벤트를 처리 (0) | 2024.11.15 |
Promise.race() 메서드 (0) | 2024.11.15 |
비동기 작업 문제 해결 방법 Callback, Promise, Async/Await. (0) | 2024.11.15 |