2008년 11월 18일 화요일

pthread와 condition variable

일단 pthread관련한 전반적인 내용은 ...

https://computing.llnl.gov/tutorials/pthreads/#Thread


pthread가 제공하는 조건 변수 관련 함수들(pthread_cond_wait, pthread_cond_signal etc.)을 제공하는 이유는 무엇일까 ?

이를 이해하기 위해서 반대로 조건 변수를 사용하지 않을 경우 어떤 불편이 있는지 살펴보자.

while(1)
{
 pthread_mutex_lock(&mutex_test);
 if(cond_var>=condition)
 {
  do_something();
  cond_var--;
  pthread_mutex_unlock(&mutex_test);
  break;
 }
 pthread_mutex_unlock(&mutex_test);
};

위 코드는 조건 변수를 확인하기 위해서 계속적으로 CPU를 소모하며 polling을 해야 하므로 효율적이지 못하다. pthread_cond_xxx를 사용하면 아래와 같이 개선할 수 있다.

1: pthread_mutex_lock(&mutex_test);
2: while(cond_var < condition)
3:  pthread_cond_wait(...);
4: do_something();
5: cond_var--;
6: pthread_mutex_unlock((&mutex_test);

- Line 1에서 mutex lock.
- Line 3에서는 아래와 같은 일들이 벌어진다.
- mutex unlock
- pthread_condition_signal이나 pthread_condition_broadcast가 호출될 때까지 block
- mutex lock
- Line 4,5 실행
- Line 6에서 mutex unlock.

Line2에서 if대신 while을 사용한 것에 주목할 필요가 있다. 이는 pthread_conditon_wait가 여러 thread에서 호출하였을 경우 먼저 스케쥴된 thread에서 cond_var--이 실행되기 때문에 나중에 스케쥴된 thread를 다시 재우기 위함이다.