c++ - check flag before pthread_cond_wait() -
bool flag=false; pthread_mutex_t mutex=pthread_mutex_initializer; pthread_cond_t cond=pthread_cond_initializer; void function1() { pthread_mutex_lock(&mutex); while(!flag) { //#2 pthread_cond_wait(&cond,&mutex); } pthread_mutex_unlock(&mutex); } void function2() { flag=true; pthread_cond_signal(&cond); } here's situation. 2 threads:thread1 , thread2 running on function1 , function2 respectively.
thread1 stops @ #2 because of cpu schedule.
thread2 begins execution , changed flag true.
thread1 begins wait wait forever.
how avoid situation when want notify other thread without locking mutex.
this why must lock mutex when update predicate (flag). there no alternative.
pthread_mutex_lock(&mutex); flag = true; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); (you can move pthread_cond_signal() after pthread_mutex_unlock() if want).
Comments
Post a Comment