Back To Interprocess Communication

Critical Section
     the part of the program where the shared memory is accessed.

The three requirements for solving the critical section problem:

Process Synchronization:
The Producer-Consumer 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)
{
    while(counter == 0);  //if buffer is empty, wait
    nextc = buffer[out];
    out = (out + 1) % n;
    counter = counter - 1;
    Consume(nextc);
}
The problem occurred at sharing the same memory space, counter.
If both read and write counter at same time,  it will cause inconsistent.
e.g. Both got counter = 3
then producer update it into 4 then consumer writes it into 2.
This looks like that the producer has never updated the information.

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.

2 operations:


Example:
            semaphore  S(0);
            p1:
                Statement 1;
                S.signal();
                Statement 3;
            p2:
                S.wait();
                Statement 2;

  For the sequence of execution,

Busy Waiting - The process is looping or running while waiting.

Two operations (OS level)

Monitor - high level abstraction for process synchronization problem solving.
See Figure 2-13 on page 69:
monitor example
integer i;
condition c;

procedure producer (x);
.
.
.
end;

procedure consummer (x);
.
.
.
end;

end monitor;
See Figure 2-14 on page 71:
An outline of the producer-consumer problem with monitors.  Only one monitor procedure at a time is active.  The buffer has N slots.
monitor Producer-Consummer
integer full, empty;
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;

end monitor;

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;

Message Passing: