Question: 2 . ( 2 0 points ) Process Synchronization This problem involves multiple readers and one writer accessing a shared resource. When the writer wants

2.(20 points) Process Synchronization
This problem involves multiple readers and one writer accessing a shared resource. When the writer wants to write, readers must wait, ensuring the writer gets priority. We will use a new API pthread_cond_broadcast(\&cond) to wake up all waiting threads on the conditional variable cond.
Please fill in 10 blanks to correctly implement synchronization using mutex locks and condition variables.
```
#include
#include
#include
int read_count =0; // Number of active readers
int writer_waiting =0; // Is the writer waiting?
```
pthread_mutex_t read_count_mutex; // Protects the read_count variable
pthread_mutex_t writer_mutex; // Controls writer's priority and access
pthread_cond_t reader_cond; // Condition variable for readers
pthread_cond_t writer_cond; // Condition variable for the writer
void* reader(void* arg){
// Lock to modify read_count
pthread_mutex_lock(______); //(1) Lock read_count_mutex to access read_count
// Wait if the writer is waiting
while {//(2) Check if the writer is waiting
pthread_cond_wait(___, &read_count_mutex); //(3) Wait for the writer
}
read_count++; // Increment reader count
pthread_mutex_unlock(&read_count_mutex); // Unlock read_count_mutex
// Reading section
printf("Reader %d is reading.
", id);
// Lock to decrement read_count
pthread_mutex_lock(&read_count_mutex); // Lock read_count_mutex
read_count--; // Decrement reader count
// If no readers are active, signal the writer
if (____){//(4) Check if no readers are active
pthread_cond_signall ; //(5) Signal the writer
}
pthread_mutex_unlock(&read_count_mutex); // Unlock read_count_mutex
return NULL;
}
void* writer(void* arg){
// Lock to manage writer state and access
pthread_mutex_lock(_____); //(6) Lock writer_mutex to access writer state
writer_waiting =1; // Mark the writer as waiting
// Wait until all readers are done
pthread_mutex_lock(&read_count_mutex); // Lock read_count_mutex
while (___){//(7) Check if any readers are active
pthread_cond_wait , &read_count_mutex); //(8) Wait for readers to finish
}
pthread_mutex_unlock(&read_count_mutex); // Unlock read_count_mutex
// Writing section
printf("Writer %d is writing.
", id);
writer_waiting =0; // Mark the writer as not waiting
// Signal waiting readers to proceed
pthread_cond_broadcast(_____); //(9) Broadcast to readers
pthread_mutex_unlock(_____); //(10) Unlock writer_mutex
return NULL;
}
2 . ( 2 0 points ) Process Synchronization This

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!