EXAMPLE FILE: misuseOfSem



//////////////////////////////////////
 AN EXAMPLE OF MIS-USE OF A SEMAPHORE
//////////////////////////////////////

(In this example, the way the semaphore is used completely
defeats its purpose.)

Below is displayed a pseudo-code version of a portion of a
student's attempt to solve a synchronization problem in which
multiple readers and multiple writers could be concurrently
accessing a shared buffer.  The code shown is executed by a
writer.  The student creating the code intended that all
processes wanting either to read or write the buffer should
wait first on a semaphore.  However, the student realized that
a writer, after waiting on the semaphore, might then gain
access to the buffer at a time when there was still data left
in the buffer by the previous writer that had not yet been seen
by any reader.  The "solution" that the student arrived at was
to create the code below for the writer:

flag = false;
do
 {
  WAIT on the semaphore guarding the buffer.
  if this buffer is marked "empty" 
   {  then
	 write information to the bufffer.
	 mark the buffer "not empty".
         flag = true ;
   }
   SIGNAL on the semaphore guarding the buffer.
 } 
while(flag == false);

Unfortunately this code creates other problems:  The loop
introduces busy waiting and indefinite postponement.  Usually,
a loop in an entry section which sends a process back
repeatedly to wait on the same semaphore for the same reason,
is misusing the semaphore. If a writer executing this code is
unlucky, he will continue to find the buffer full each time he
waits.  There is no limit to how long this could continue.