pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t readerQ = PTHREAD_COND_INITIALIZER; pthread_cond_t writerQ = PTHREAD_COND_INITIALIZER; int readers = 0; int writers = 0; reader( ) { pthread_mutex_lock(&m); while (!(writers == 0)) { pthread_cond_wait(&readersQ, &m); } readers++; pthread_mutex_unlock(&m); /* read */ pthread_mutex_lock(&m); if (--readers == 0) { pthread_cond_signal(&writersQ); } pthread_mutex_unlock(&m); } writer( ) { pthread_mutex_lock(&m); while(!((readers == 0) && (writers == 0))) { pthread_cond_wait(&writersQ, &m); } writers++; pthread_mutex_unlock(&m); /* write */ pthread_mutex_lock(&m); writers--; pthread_cond_signal(&writersQ); pthread_cond_broadcast(&readersQ); pthread_mutex_unlock(&m); }
Writers can 'starve' with this code. That is, a waiting writer may be indefinitely prevented from writing? How might this happen?