Reader/Writer with Semaphores in C
Implement a fair solution in C with readers and writers followingthe synchronization scheme of the course notes.
In the template below, there is only a single reader and a singlewriter. The reader busily keeps reading all the
time and computes the maximum of all numbers read. The writergenerates in 1 second intervals numbers 0 ..
maxIters starting from the middle one and wrapping around, i.e.generating the maximum after about half the
iterations. The variable maxIters is the command line parameter.The synchronization scheme has to ensure
that the writer is given preference, so in case there is more thanone reader, all readers have a chance to get the
updates from the single writer. Your solution has to be correct formultiple readers and multiple writers, even if
the code below creates only a single reader and a singlewriter.
By default, threads are created as demon threads, meaning that ifthe main program terminates, all demon
threads terminate as well. Below, the main program waits only forthe writer to terminate; when the main program
terminates, the reader will terminate as well.
Be careful to declare only those variables volatile that need to bedeclared so, as otherwise the program
may run slower unnecessarily. Play around to see what happens ifyou don’t declare variables volatile !
%%writefile rw.c
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#define SHARED 1
void *Reader(void *); /* the two threads */
void *Writer(void *);
/* global varialbes and semaphores */
// YOUR CODE HERE
int numIters;
/* main program: read command line, create threads, print result of*/
int main(int argc, char *argv[]) {
pthread_t rid, wid; /* thread and attributes */
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
/* initialization of global varialbes and semaphores */
// YOUR CODE HERE
numIters = atoi(argv[1]);
pthread_create(&rid, &attr, Reader, NULL);
pthread_create(&wid, &attr, Writer, NULL);
pthread_join(wid, NULL);
printf(“Max data %dn”, maxdata);
}
/* deposit 1, …, numIters into the data buffer */
void *Reader(void *arg) {
maxdata = 0;
printf(“Reader startingn”);
while (1) {
/* entry protocol */
// YOUR CODE HERE
if (data > maxdata) printf(“maxdata %dn”, data);
maxdata = data > maxdata ? data : maxdata;
/* exit protocol */
// YOUR CODE HERE
}
}
/* fetch numIters items from the buffer and sum them */
void *Writer(void *arg) {
int i;
printf(“Writer startingn”);
for (i = 0; i < numIters; i++) {
/* entry protocol */
// YOUR CODE HERE
data = (i + numIters / 2) % numIters;
printf(“Writer writing %dn”, data);
/* exit protocol */
// YOUR CODE HERE
sleep(1);
}
}
Expert Answer
Answer to Reader/Writer with Semaphores in C Implement a fair solution in C with readers and writers following the synchronization…