-
Runtime / Execution Stack / Task Queue개발/Javascript 2022. 6. 6. 14:40
*복습 자료라서 뻔한 내용은 생략
Summary.
1. Javascript 가 나올 당시 멀티프로세서도 별로 없고, 사용처도 적어서 Single threaded Language가 당연했음
+ 더 높은 성능을 감당하기 위해서 task scheduling, 등, 다양한 기능 추가됨
2. 모든 코드 fragment 동작 시 execution context가 생성됨 (OS에서 배운 Execution Frame 생각하면 됨)
+ 세 종류 context: global (함수 밖), local (함수 안), eval context
+ 모든 execution context는 생성 시 stack에서 관리됨 (execution context stack)
+ 최종적으로 main program 끝나고 처음에 push 된 global context도 pop되면 프로그램 종료됨
+ execution context 통해서 변수, scope, 함수 실행 및 반환, 등이 관리됨
3. Javascript Runtime Engine은 여러 agent를 가지고 있음. 이 agent들은 각각 고유의 execution stack, task/microtask queue, main thread, additional threads to manage workers 를 가짐 (main thread만 shared)
4. 각 agent 는 event loop에 의해 동작됨. event loop이 queue에 추가한 task들에 대해서 task queue -> microtask queue -> rendering & painting 순으로 반복 실행됨
+ Event Loop 종류: Window Event Loop, Worker Event Loop, Worklet Event Loop이 있음
+ Window는 Browser에서 정의되는 Container 단위로 실제 Window, Tab, Frame, 등을 말함
+ Worker는 하나 혹은 여러 Agent에 귀속되고, basic web worker, service worker, shared worker, 등이 있음
+ Web Worker allows the main script to run other scripts in new threads
+ The Worklet interface is a lightweight version of Web Workers and gives developers access to low-level parts of the rendering pipeline.
+ 같은 origin을 가지는 Window 끼리는 Event Loop 공유함 (브라우저마다 다름)
+ 특정 Event Loop이 마비되면 해당 Event Loop을 공유하는 Thread들도 마비됨
+ https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth#event_loops
5. A task is any JavaScript scheduled to be run by the standard mechanisms
+ setTimeout, setInterval 함수호출이나 Event로 등록됨
+ 매 Event Loop iteration이 시작할 때 처리되므로 iteration 중간에 task queue에 들어가도 다음 iteration까지 실행 안됨
6. Each time a task exits, and the execution context stack is empty, each microtask in the microtask queue is executed
+ microtask는 중도 추가돼도 다음 iteration 전까지 반드시 수행됨
7. Web Worker은 Main Thread 부담을 줄여주기 위함이고 MicroTask는 세밀한 스케줄링을 위함 (queueMicrotask(), 등)
8. A JavaScript runtime uses a message queue, which is a list of messages to be processed. Each message has an associated function that gets called to handle the message (message는 해당 function의 input이 되고, 해당 message 처리가 끝나면 (즉, stack이 비면) 다시 queue에서 새로운 message를 처리함)
+ preemption 없이 확실히 해당 task 작업을 다 끝마쳐야 다음 task를 시작함 (queue 내 task 간 context switching 없다는 것)
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#queue
9. Event Loop은 대략 아래와 같이 동작함
while (queue.waitForMessage()) { queue.processNextMessage() }
Additional.
1. 다른 Runtime 간 통신도 가능 (Worker, iframe, 등은 각각 stack, heap, queue를 가지는데 postMessage로 통신 가능)
2. (다음에) node.js event loop 세부 동작
+ https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#what-is-the-event-loop
Reference.
'개발 > Javascript' 카테고리의 다른 글
Strict Mode (0) 2022.06.06 History (ECMAScript) (0) 2022.06.06 Promise & Async, Await (0) 2022.06.06 Module System (0) 2022.06.05 Prototype Chain (0) 2022.06.05