next up previous
Next: Message Passing Up: No Title Previous: Monitors

Readers and Writers via semaphores

VAR rc = 0 : integer {reader count}
    mutex = 1 : semaphore ;
    access = 1 : semaphore ;
Process READER
loop
  P(mutex) ; {get mutual exclusion to rc}
  rc := rc + 1 ;
  if rc = 1 then P(access) end ;
  {first reader gets exclusive access to database
   if writer accessing then block - following readers
   block on mutex}
  V(mutex); {release mutual exclusion to rc}
  {read database} ;
  P(mutex) ;
  rc := rc - 1 ;
  If rc = 0 then V(access) end ;
  {if last reader, release database for writers} 
  V(mutex) ; 
  {use data}
end ; 

Process WRITER 
loop
  {generate data}
  P(access) ; {get mutual exclusion to database}
  {write to database}
  V(access) ; {release mutual exclusion to database}
end ;



Omer F Rana
Tue Feb 11 19:19:52 GMT 1997