Critical Section
the part of the program where the shared memory
is accessed.
The three requirements for solving the critical section problem:
Producer:
while(true)
{
Produce(nextp);
while(counter == n); //if buffer is full, wait
buffer[in] = nextp;
in = (in + 1) % n; //mode by n
counter = counter + 1;
}
Consumer:
while(true)The problem occurred at sharing the same memory space, counter.
{
while(counter == 0); //if buffer is empty, wait
nextc = buffer[out];
out = (out + 1) % n;
counter = counter - 1;
Consume(nextc);
}
Solving the Producer-Consumer Problem using Semaphores:
Semaphores:
(Synchronization tool) (Dijkstra 1965)
It is an integer variable which is accessed
through two atomic operations:
wait , signal
down, up
sleep, wakeup
P, V (original in Dutch)
Note: Atomic means that it can not be divided.
So, either completed all or not done at all.
class semaphore
{
public:
semaphore(int
i) // constructor
{
S = i;
}
void
wait() // atomic operation
{
while(S <= 0);
S = S - 1;
}
void
signal() // atomic operation
{
S = S + 1;
}
private:
int S; //S is a waiting queue.
}
semaphore mutex(1);
//mutual exclusion object: mutex
pi:
while(true)
{
mutex.wait();
critical section
mutex.signal();
remainder section
}
Example:
semaphore S(0);
p1:
Statement 1;
S.signal();
Statement 3;
p2:
S.wait();
Statement 2;
For the sequence of execution,
Two operations (OS level)
monitor exampleSee Figure 2-14 on page 71:integer i;end monitor;
condition c;procedure producer (x);
.
.
.
end;procedure consummer (x);
.
.
.
end;
monitor Producer-Consummer
Message Passing:integer full, empty;end monitor;
condition count;procedure enter;
begin
if count = N then wait(full);
enter_item;
count := count + 1;
if count = 1 then signal(empty)
end;procedure remove;
begin
if count = 0 then wait(empty);
remove_item;
count := count - 1;
if count = N - 1 then signal(full)
end;count := 0;
procedure producer;
begin
while truedo
begin
produce_item;
Producer-Consummer.enter
end
end;procedure consumer;
begin
while truedo
begin
Producer-Consummer.enter;
consumer_item
end
end;