- thread는 실행을 하기 전에 어떤 조건이 참인지 확인하려고 함 → conditonal variable
- Parent Waiting for child : Spin-based Approach
- Wait for a Condition
- Waiting on the condition : 쉴 테니까 되면 불러 ㅋ 하고 queue 들감
- Signaling on the condiont : 조건 주는 애한테 signal
- definition and routines
- 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; }
- 문제 A: done 변수 두는 이유?
- join이 먼저 불릴 것이라는 보장이 없음. 그 상황에서 join 불렀을 때 아무도 깨워주지 않는 상황이 발생할 수 있기 때문
- 문제 B: lock이 없으면 어떤 문제?
- join에서 cond_wait이 일어나기 전, 즉 자러 가기 전에 context switch 가 발생해서 done이 1로 바뀌면 깨워줄 사람이 없음
- 문제 C: 조건 변수 → 조건이 만족되었나 체크하기 위해 반드시 필요
- 결론: 이렇게 해서 CPU 자원을 아끼고자 함
- 문제 A: done 변수 두는 이유?
- Producer / Consumer (bound buffer) problem
- Producer
- 데이터 아이템 생성
- data item들을 buffer에 넣음
- Consumer
- data item들을 buffer 바깥으로 꺼내 어떤 방식으로 소모를 함
- Producer
반응형