Question: 2 . ( 2 0 points ) Process Synchronization This problem involves multiple readers and one writer accessing a shared resource. When the writer wants
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 pthreadcondbroadcast&cond to wake up all waiting threads on the conditional variable cond.
Please fill in blanks to correctly implement synchronization using mutex locks and condition variables.
#include
#include
#include
int readcount ; Number of active readers
int writerwaiting ; Is the writer waiting?
pthreadmutext readcountmutex; Protects the readcount variable
pthreadmutext writermutex; Controls writer's priority and access
pthreadcondt readercond; Condition variable for readers
pthreadcondt writercond; Condition variable for the writer
void readervoid arg
Lock to modify readcount
pthreadmutexlock; Lock readcountmutex to access readcount
Wait if the writer is waiting
while Check if the writer is waiting
pthreadcondwait &readcountmutex; Wait for the writer
readcount; Increment reader count
pthreadmutexunlock&readcountmutex; Unlock readcountmutex
Reading section
printfReader d is reading.
id;
Lock to decrement readcount
pthreadmutexlock&readcountmutex; Lock readcountmutex
readcount; Decrement reader count
If no readers are active, signal the writer
if Check if no readers are active
pthreadcondsignall ; Signal the writer
pthreadmutexunlock&readcountmutex; Unlock readcountmutex
return NULL;
void writervoid arg
Lock to manage writer state and access
pthreadmutexlock; Lock writermutex to access writer state
writerwaiting ; Mark the writer as waiting
Wait until all readers are done
pthreadmutexlock&readcountmutex; Lock readcountmutex
while Check if any readers are active
pthreadcondwait &readcountmutex; Wait for readers to finish
pthreadmutexunlock&readcountmutex; Unlock readcountmutex
Writing section
printfWriter d is writing.
id;
writerwaiting ; Mark the writer as not waiting
Signal waiting readers to proceed
pthreadcondbroadcast; Broadcast to readers
pthreadmutexunlock; Unlock writermutex
return NULL;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
