Guarantee on condition variable predicate/pthreads?
Pete Sheridan wrote: > Thread 2: > pthread_mutex_lock(&m); > if (n != 0) > { > pthread_cond_wait(&m, &c); > assert(n == 0); > } > pthread_mutex_unlock(&m); > > The idea here is that thread 2 wants to wake up when n is 0. Is the > assert() correct? i.e., will n always be 0 at that point? When the > condition is signalled, thread 2 has to reacquire the mutex. Thread 1 > may get the mutex first, however, and increment n before this happens. > Is this implementation dependent? Or does thread 2 have to use “while > (n != 0)” instead of “if (n != 0)”? The assert() is incorrect. The POSIX standard carefully allows for a condition wait to return “spuriously”. I won’t go into all the details, but allowing spurious wakeups is good for both the implementation and the application. (You can do a search on Deja News if you really want to know, because I’ve explained this several times before; or you can read my book, about which you may learn through the www.awl.com link below.) To correct Thread 2,