ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > ZSTU-(2020-2021)-1 > student homework > >
homework6 Version 0
👤 Author: by 1730854984qqcom 2020-11-06 13:32:36
Hardware-based solutions to the critical section problem are complex to use for application programmers. To overcome this difficulty, a synchronization tool called a semaphore can be used. The semaphore S is an integer variable that, in addition to initialization, can only be accessed through two standard atomic operations: wait() and signal().
wait(S){
while(S<=0)
,//no-op
S--;
}
signal(S){
S++;
}


All modifications to the integer value of the semaphore in the wait() and signal() operations must be executed atomically. That is, when one process modifies the semaphore value, no other process can simultaneously modify that same semaphore value. In addition, in the case of wait(S), the testing of the integer value of S (S ≤ 0), as well as its possible modification (S--), must be executed without interruption.

In this question, I choose the reader/writer question of the book. I assume that reading and writing is fair. If the reader is already queued, even if the writer gets the resource, it waits for all waiting readers to finish the process.
int count=0;
semaphore mutex=1; //读者计数锁
semaphore rw=1; //资源访问锁
semaphore w=1; //读写公平抢占锁
writer()
{
while(1)
{
P(w);
P(rw);
writing sth;
V(rw);
V(w);
}
}

reader()
{
while(1)
{
P(w);
P(mutex);
if(count==0)
P(rw);
count++;
V(mutex);
V(w);
reading sth;
P(mutex);
count--;
if(count==0)
V(rw);
V(mutex);
}
}

Please login to reply. Login

Reversion History

Loading...
No reversions found.