// shared pthead_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;
The reader and writer code:
void reader() void writer() { { pthread_mutex_lock(&m); pthread_mutex_lock(&m); while(!(writers == 0)) { while(!((readers == 0) && (writers == 0))) { pthread_cond_wait(&readerQ, &m); pthread_cond_wait(&writerQ, &m); } } readers++; writers++; pthread_mutex_unlock(&m); pthread_mutex_unlock(&m); // read // write pthread_mutex_lock(&m); pthread_mutex_lock(&m); if (--readers == 0) { writers--; pthread_cond_signal(&writerQ); pthread_cond_signal(&writerQ); } pthread_cond_broadcast(&readerQ); pthread_mutex_unlock(&m); pthread_mutex_unlock(&m); } }
Note: This "solution" can cause writers to starve.
It isn't too hard to devise a solution again with condition variables that avoids this problem.
A key idea is to keep a count of waiting writers and another variable for the active_writer.
Can you modify the solution above to provide this solution?