Readers and Writers Problem
/* The following code uses
a C-like syntax that includes semaphores as described in the book and a parallel_main function that invokes the
threads reader and writer in parallel using apparent concurrency. Notice that it is written for one reader and
one writer. How would you adapt it to
work for multiple readers and multiple writers? */
mutex, w
: semaphore = 1;
usecount
: integer = 0;
/*
functions open() and close() are printed side-by-side to conserve space */
void open(char mode[]) void close(char mode[])
{ {
if
(mode == read) if
(mode == read)
{ {
wait(mutex); wait(mutex);
usecount
++; usecount--
if
(usecount == 1) wait(w); if
(usecount == 0) signal(w);
signal(mutex); signal(mutex);
} }
else
wait(w); else
signal(w);
} }
/* functions reader() and
writer() are printed side-by-side to conserve space */
void
reader() void
writer()
{ {
for(;;) for(;;)
{ {
char
m[] = ‘read’; char
m[] = ‘write’;
open(m); open(m);
read for a while; write for a
while;
close(m); close(m);
} }
} }
void
parallel_main()
{
reader(); writer();
}