Readers Writers Problem Implementation in Java
This is the java program to implement readers writers problem using threads and semaphores
In computer science, the first and second readers-writers problems are examples of a common computing problem in concurrency. The two problems deal with situations in which many threads must access the same shared memory at one time, some reading and some writing, with the natural constraint that no process may access the share for reading or writing while another process is in the act of writing to it. (In particular, it is allowed for two or more readers to access the share at the same time.) A readers-writer lock is a data structure that solves one or more of the readers-writers problems.
class controller
{
int areader=0,awriter=0,wwriter=0,wreader=0;
public int allowreader()
{
int res=0;
if(wreader==0&&awriter==0)
{
res=1;
}
return res;
}
public int allowwriter()
{
int res=0;
if(areader==0&&awriter==0)
{
res=1;
}
return res;
}
synchronized void beforeread()
{
wreader++;
while(allowreader()!=0)
{
try
{
wait();
}
catch(InterruptedException e)
{
}
wreader--;
areader++;
}
}
synchronized void beforewrite()
{
wwriter++;
while(allowwriter()!=0)
{
try
{
wait();
}
catch(InterruptedException e)
{
}
wwriter--;
awriter++;
}
}
synchronized void afterread()
{
areader--;
notifyAll();
}
synchronized void afterwrite()
{
awriter--;
notifyAll();
}
}
class rew
{
static controller ctl;
public static void main(String[] args)
{
ctl=new controller();
new reader1(ctl).start();
new reader2(ctl).start();
new writer1(ctl).start();
new writer2(ctl).start();
}
}
class reader1 extends Thread
{
controller ctl;
public reader1(controller c)
{
ctl=c;
}
public void run()
{
while(true)
{
ctl.beforeread();
System.out.println("Reader1 Reading");
System.out.println("Done Reading");
ctl.afterread();
System.out.println("After Read");
}
}
}
class reader2 extends Thread
{
controller ctl;
public reader2(controller c)
{
ctl=c;
}
public void run()
{
while(true)
{
ctl.beforeread();
System.out.println("Reader2 Reading");
System.out.println("Done Reading");
ctl.afterread();
System.out.println("After Read");
}
}
}
class writer1 extends Thread
{
controller ctl;
public writer1(controller c)
{
ctl=c;
}
public void run()
{
while(true)
{
ctl.beforewrite();
System.out.println("Writer1 Writing");
System.out.println("Done Writing");
ctl.afterread();
System.out.println("After Write");
}
}
}
class writer2 extends Thread
{
controller ctl;
public writer2(controller c)
{
ctl=c;
}
public void run()
{
while(true)
{
ctl.beforewrite();
System.out.println("Writer2 Writing");
System.out.println("Done Writing");
ctl.afterread();
System.out.println("After Write");
}
}
}
Kindly explain what does the initials ‘a’ and ‘w’ mean in the variable names. it will be easier to comprehend.
and why this condition : wreader==0 in allowreader() ?