정리 노트

Limited Direct Execution(2) - Context Switch 본문

개념 정리/운영체제

Limited Direct Execution(2) - Context Switch

꿈만 꾸는 학부생 2023. 7. 23. 18:39
728x90

이 포스트는 국민대학교 소프트웨어학부 '운영체제' 강의를 듣고 요약하는 포스트입니다. 원하시는 정보가 없을 수도 있습니다. 이 점 유의 바랍니다. 오류 지적은 매우 환영합니다!


OS가 CPU 자원을 프로세스에 할당하는 방법으로 타이머를 사용합니다. 타이머도 일종의 장치이므로 CPU에게 interrupt를 걸 수 있고, 똑같이 trap handler로 진입합니다. Trap handler는 현재 진행 중인 프로세스를 중단하고 다른 프로세스로 바꿉니다. 이러한 동작을 context switch라고 합니다.

출처: https://pages.cs.wisc.edu/~remzi/OSTEP/cpu-mechanisms.pdf, 8쪽
A timer device can be programmed to raise an interrupt every so many milliseconds; when the interrupt is raised, the currently running process is halted, and a pre-configured interrupt handler in the OS runs. At this point, the OS has regained control of the CPU, and thus can do what it pleases: stop the current process, and start a different one.

source: https://pages.cs.wisc.edu/~remzi/OSTEP/cpu-mechanisms.pdf, 11쪽

Booting 단계에서 타이머를 실행하고, 일정 간격마다 CPU에게 interrupt를 겁니다.

Timer interrupt가 걸리면, kernel mode에서 현재 CPU의 레지스터 값들을 kernel stack에 저장하고, OS가 kernel stack에 저장된 값들을 메모리에 저장합니다. 이후, 메모리의 다른 곳에 적혀있던 다른 프로세스의 레지스터 값들을 kernel stack에 작성하고, 하드웨어는 kernel stack의 값을 CPU의 레지스터에 옮깁니다. 이러한 과정을 통해 context switch가 일어납니다.

 

Timer의 시간을 다 사용한 프로세스는 running 상태에서 ready 상태가 되고, ready 상태였던 다른 프로세스들 중 하나가 scheduler에 의해 선택돼 running 상태가 됩니다.

 

아래의 코드는 context switch 과정을 작성한 어셈블리 코드입니다.

source: https://pages.cs.wisc.edu/~remzi/OSTEP/cpu-mechanisms.pdf, 12쪽

728x90