수정입니다

26. Concurrency : An Introduction 본문

전공/운영체제

26. Concurrency : An Introduction

nongdamgom 2024. 1. 15. 01:18

 

Thread ?
  • a new abstraction for a single running process
Multi - threaded program
  • 하나 이상의 execution point를 가지는 program
  • cpu 안에 pc는 하나인데 어떻게 multi thread?
  • => context switching 하는 것 처럼 thread들을 계속 빠른 시기에 바꿔줌
  • excution point 가 여러개 == PCB의 저장 공간 유무
  • => 여러 thread가 어디까지 수행했는지를 PCB에 저장해서 알 수 있어야 함
  •  
  • 보통 thread 들은 하나의 process에서 address space를 공유한다.
  • => PDBR을 바꿀 필요가 x => page table 바꿀 필요 x => memory 접근 안해도 됨 
  • ==> communication overhead가 줄어든다.

 

 

Context switch between threads

  • 각 thread는 자신만의 program counter와 set of registers를 가짐
  • => 이 상태를 저장하기 위해 하나 이상의 thread contorl blocks(TCBs) 필요
  • T1 => T2 변경
  1. T1의 reg 상태 저장
  2. T2의 reg 상태 복원
  3. kernel stack 변경 (하는 일이 thread 마다 다르기 때문에, stack이 다르므로 바꿔줘야 함)

 

Race condition

  • 여러개의 thread가 동시에 같은 작업을 했을 때, 서로에게 좋지 않은 영향을 미침

  • 만약 두 thread가 동시에 +1을 했다고 하면 +2가 될 걸 기대하지만, +1이 될 가능성이 있음
  • counter = counter + 1 라는 명령을 assembly로 바꾸면, 세개의 명령어로 나뉘는데
  • 중간에 interrupt가 들어오면, store 하지 못한 상태에서 바뀌고, old value를 새 thread가 load 하게 됨

 

 

Critical section

  • 위와 같은 문제가 발생하는건 여러 thread가 accesses a shared variable 할 때만 문제 발생
  • => local variable이면 어차피 각자 실행하니까 문제 없음
  • 해결을 위해 mutual exclusion이 필요하다 (atomicity for critical section)
  • => T1이 critical section 수행하는 동안 어떤 thread도 그 section을 수행 불가 하게 만들겠다는 뜻

 

 

Locks

  • lock, unlock을 통해 critical section을 single atomic instruction으로 만들어줌

 

 

Why hardware support needed?

typedef struct __lock_t { int flag; } lock_t;

void init(lock_t *mutex){
	mutex->flag = 0;
}

void lock(lock_t *mutex){
	while(mutex->flag == 1)  // 1이면 대기
    	;  // spin - wait
    mutex->flag = 1;  // 사용하고 있는 thread가 1로 setting 해서 위에서 다른 thread 침입 막음
}

void unlock(lock_t *mutex){
	mutex->flag = 0;  //unlock 후 다시 0으로 만들어서 대기 풀어줌
}
  • First attempt => using flag
  • flag = 0으로 초기화 해 두고, flag = 1일 때 무한 대기 loop  
  • 이 때 사용되는 loop 명령들이, 100% cpu 명령이라 loop 탈출 때까지 cpu과열 => 낭비 됨

 

Problem 1 : No Mutual Exclusion

 

Problem 2 : Spin-wating wastes time wating for another thread

 

 

==> Hardware의 도움을 받으면 problem 1은 해결할 수 있음

==> test-and-set instruction 이용 (atomic exchange)

'전공 > 운영체제' 카테고리의 다른 글

28. Locks  (1) 2024.01.15
27. Interlude : Thread API  (0) 2024.01.15
20. Paging: Smaller Tables  (1) 2024.01.14
19. Translation Lookaside Buffers  (1) 2024.01.14
18. Paging: Introduction  (0) 2024.01.14