HW5 Version 0 |
|
👤 Author: by 627864699qqcom 2020-11-03 11:14:05 |
To deal with this problem, we use a method named semaphore.
Define as:
typedef struct {
int value;
struct process *list;
} semaphore;
//initialized
semaphore mtx=1, wrt=1;
int readcount=0;
The semaphore wrt is common to both reader and writer processes. The mutex semaphore is used to ensure mutual exclusion when the variable readcount is updated. The readcount variable keeps track of how many processes are currently reading the object. The semaphore wrt functions as a mutual-exclusion semaphore for the writers. It is also used by the first or last.
while(TRUE)
{
wait(wrt);
signal(wrt);
} ;
Reader:
while(TRUE)
{
wait(mtx);
readcount++;
if (readcount==1)
wait(wrt);
signal(mtx);
wait(mtx);
readcount--;
if (readcount == 0)
signal(wrt);
signal(mtx);
} ;