0

How to implement a solution to Readers-Writers problem using writers preference

So I just now got into Multithreading and encountered the Readers-Writers problem. In the following case: -The driver creates 500 Reader threads and 500 Writer threads. After all threads have been started the driver waits for them to finish. -Each Writer thread attempts to open a text file that contains a single number. If the file doesn't exist then the writer will create the file and store the number 1 in the file. If the file does exist the writer will read the value, add one to it and write the new value back to the file (replacing the original value). -Each Reader will read the value from the file and display it. If the file doesn't exist it reports the error without crashing. I have to modify the program so it employs a Writer-Preference solution to this instance of the Readers-Writers Problem. The basic logic of the provided code should remain intact. Here are the following codes: Driver - https://code.sololearn.com/cvbJnSbFXeEF Reader - https://code.sololearn.com/c6i4eyhG071L Writer - https://code.sololearn.com/c96698rqEgza If anyone can help me, I would really appreciate it!

18th Nov 2019, 7:42 PM
Spartan Noah- 458
Spartan Noah- 458 - avatar
1 Answer
+ 1
int readcount, writecount = 0; semaphore rsem, wsem = 1; // semaphore x,y,z = 1; // void main(){ int p = fork(); if(p) reader; // assume multiple instances else writer; // assume multiple instances } void reader(){ while(1){ wait(z); wait(rsem); wait(x); readcount++; if (readcount==1) wait(wsem); signal(x); signal(rsem); signal(z); doReading(); wait(x); readcount--; if (readcount==0) signal(wsem); signal(x); } } void writer(){ while(1){ wait(y); writecount++; if (writecount==1) wait(rsem); signal(y); wait(wsem); doWriting(); signal(wsem); wait(y); writecount--; if (writecount==0) signal(rsem); signal(y); } }
1st Mar 2020, 1:32 PM
ROBIN C R
ROBIN C R - avatar