Producer-Consumer ,: The Reader-Writer Problems and Solving Them by Semaphore
Producer-Consumer ,: The Reader-Writer Problems and Solving Them by Semaphore
: إعداد
محمد محمد جمعة محمد شبانة
) 3 ( سكشن
The Solutions
we use three semaphore variables
Procedure code :
void producer() {
while(T) {
produce()
wait(E)
wait(S)
append()
signal(S)
signal(F)
}
}
Consumer Code :
void consumer() {
while(T) {
wait(F)
wait(S)
take()
signal(S)
signal(E)
use()
}
}
signal(E) —› increase the semaphore variable "E" by one.
Use() is a function that is used to use the data taken from the buffer
by the process to do some operation.
we deal with various processes and these processes may use files that
are present in the system. Basically, we perform two operations on a
file “read and write”. All these processes can perform these two
operations. But the problem that arises here is that:
The Solutions
By using semaphore, we can solve these problems but
we have one variable readerCount that will have the count of the
processes that are reading a particular file. The readerCount variable
is initially initialized to 0.
wait(writer)
...
write operation
...
signal(writer)
• The wait(writer) function is called so that it achieves the mutual
exclusion. The wait () function will reduce the writer value to "0"
and this will block other processes to enter into the critical section.
• The write operation will be carried and finally,
the signal(writer) function will be called, and the value of
the writer will be again set to "1" and now other processes will be
allowed to enter into the critical section.
Ex:
wait(mutex) |
readerCount++ |
if(readerCount == 1) |--- changing the readerCount
wait(writer) |
signal(mutex)
...
read operation
wait(mutex)
readerCount-- |
if(readerCount == 0) |--- changing the readerCount
signal(writer) |
signal(mutex)