sem_t read_mutex, write_mutex, write_count_mutex;
int read_count = 0;
int write_count = 0;
void* reader_entry(void* arg) {
int id = (int)arg;
while (1) {
// Acquire the read_mutex
sem_wait(&read_mutex);
code
// Increment the read_count
read_count++;
if (read_count == 1) {
// If this is the first reader, acquire the write_mutex
sem_wait(&write_mutex);
}
// Release the read_mutex
sem_post(&read_mutex);
printf("Reader %d: Reading\n", id);
sleep(2);
// Acquire the read_mutex
sem_wait(&read_mutex);
// Decrement the read_count
read_count--;
if (read_count == 0) {
// If this is the last reader, release the write_mutex
sem_post(&write_mutex);
}
// Release the read_mutex
sem_post(&read_mutex);
printf("Reader %d: Finished Reading\n", id);
sleep(rand() % 5);
}
}
void* writer_entry(void* arg) {
int id = (int)arg;
while (1) {
// Acquire the write_count_mutex to protect write_count
sem_wait(&write_count_mutex);
code
// Increment the write_count
write_count++;
if (write_count == 1) {
// If this is the first writer, acquire the read_mutex
sem_wait(&read_mutex);
}
// Release the write_count_mutex
sem_post(&write_count_mutex);
// Acquire the write_mutex
sem_wait(&write_mutex);
// Critical section
printf("Writer %d: Writing\n", id);
sleep(3);
printf("Writer %d: Finished Writing\n", id);
// Release the write_mutex
sem_post(&write_mutex);
// Acquire the write_count_mutex
sem_wait(&write_count_mutex);
// Decrement the write_count
write_count--;
if (write_count == 0) {
// If this is the last writer, release the read_mutex
sem_post(&read_mutex);
}
// Release the write_count_mutex
sem_post(&write_count_mutex);
sleep(rand() % 5);