c++ - avoiding deadlock when pthread_cond_wait and pthread_cond_signal -
i have question regarding use of pthread condition variables. general use case this
//thread 1: pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); do_something() pthread_mutex_unlock(&mutex); //thread 2: pthread_cond_signal(&cond);
now know pthead_cond_wait unlock mutex , go sleep , when awaken lock mutex , return call how ensure signal thread 2 reaches thread 1 after thread 1 in condition wait. occur thread2 runs first , thread1 causing lost wake up.
if use mutex lock in thread 2 again may happen thread2 lock signal , thread1 still trying acquire lock. again result in lost wake up.
how ensure signal condition variable reaches thread waiting on ?
thanks
you "general use case" not correct. condition variable must paired condition on shared state, known predicate. general use case is:
thread 1:
pthread_mutex_lock(&mutex); while (!condition) pthread_cond_wait(&cond, &mutex); do_something(); /* requiring 'condition' true */ pthread_mutex_unlock(&mutex);
thread 2:
pthread_mutex_lock(&mutex); do_something_else(); /* sets 'condition' true */ pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex);
...where condition
on shared state protected mutex
- example, condition
might checking shared queue non-empty.
there can no lost wakeup in structure, because waiting thread always checks condition before waiting. if condition true, doesn't wait - , because holds mutex protecting condition, can't become true between check , wait either.
(note pthread_cond_broadcast()
correct function use, , pthread_cond_signal()
optimisation applicable in many cases).
Comments
Post a Comment