본문 바로가기

OS

[운영체제] 13. Conditional Variables

  1. thread는 실행을 하기 전에 어떤 조건이 참인지 확인하려고 함 → conditonal variable
  2. Parent Waiting for child : Spin-based Approach
  3. Wait for a Condition
    1. Waiting on the condition : 쉴 테니까 되면 불러 ㅋ 하고 queue 들감
    2. Signaling on the condiont : 조건 주는 애한테 signal
  4. definition and routines
  5. condition variable 사용한 code
    int done = 0;
    pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t c = PTHREAD_COND_INITIALIZER;
    
    void thr_exit() {
    		Pthread_mutex_lock(&m);
    		done = 1;
    		Pthread_cond_signal(&c);
    		Pthread_mutex_unlock(&m);
    }
    
    void *child(void *arg){
    		printf("child\n");
    		thr_exit();
    		return NULL;
    }
    
    void thr_join() {
    		Pthread_mutex_lock(&m);
    		while (done == 0)
    			Pthread_cond_wait(&c, &m);
    		Pthread_mutex_unlock(&m);
    }
    
    int main(int argc, char *argv[]) {
    		printf("parent: begin\n");
    		pthread_t p;
    		pthread_create(&p, NULL, child, NULL);
    		thr_join();
    		printf("parent: end\n");
    		return 0;
    }​
    1. 문제 A: done 변수 두는 이유?
      1. join이 먼저 불릴 것이라는 보장이 없음. 그 상황에서 join 불렀을 때 아무도 깨워주지 않는 상황이 발생할 수 있기 때문
    2. 문제 B: lock이 없으면 어떤 문제?
      1. join에서 cond_wait이 일어나기 전, 즉 자러 가기 전에 context switch 가 발생해서 done이 1로 바뀌면 깨워줄 사람이 없음
    3. 문제 C: 조건 변수 → 조건이 만족되었나 체크하기 위해 반드시 필요
    4. 결론: 이렇게 해서 CPU 자원을 아끼고자 함
  6. Producer / Consumer (bound buffer) problem
    1. Producer
      1. 데이터 아이템 생성
      2. data item들을 buffer에 넣음
    2. Consumer
      1. data item들을 buffer 바깥으로 꺼내 어떤 방식으로 소모를 함

 

반응형