/* * Readers-writers solution with weak reader priority * Originally From Courtois et al, CACM, 1971. * via code accompanying Computer Systems: A Programmer's Perspective, 2/E (CS:APP2e) * Randal E. Bryant and David R. O'Hallaron, Carnegie Mellon University * * Minor adaptation by Brighten Godfrey * * NOTE: This program is incomplete. We haven't initialized * the global variables and haven't actually started any * readers / writers. So it doesn't do very much. :-) */ #include #include #include #include #include /* Global variables */ int readcnt; /* Initially = 0 */ sem_t mutex, w; /* Both initially = 1 */ void reader(void) { while (1) { sem_wait(&mutex); readcnt++; if (readcnt == 1) /* First in */ sem_wait(&w); /* lock out writers */ sem_post(&mutex); /* Main critical section */ /* Reading would happen here */ sem_wait(&mutex); readcnt--; if (readcnt == 0) /* Last out */ sem_post(&w); /* let in writers */ sem_post(&mutex); } } void writer(void) { while (1) { sem_wait(&w); /* Critical section */ /* Writing would happen here */ sem_post(&w); } }