Program mutex2
// CS237 - Busy waiting example 2
// ==============================
// Second attempt at solving the MEP
// using a `flag of intention' approach.
// This is unsafe!
class mutex2 extends Thread
{
static int N = 2 ; // Number of processes.
static boolean flag [] = new boolean[N] ;
private int id ;
public mutex2(int i)
{
id = i ;
}
private int random(int n)
{
return (int) Math.round( n * Math.random() - 0.5 ) ;
}
private void busy()
{
try{ sleep(random(500)) ; } catch (InterruptedException e) { }
}
private void noncritical()
{
System.out.println("Process "+id+" is NON critical") ;
busy() ;
}
private void critical()
{
System.out.println("Process "+id+" entering critical section") ;
busy() ;
System.out.println("Process "+id+" leaving critical section") ;
}
private boolean wait(int i)
{
boolean r = false ;
for (int j = 0 ; j < N ; j++) if (j != i) r = r | flag[j] ;
return r ;
}
private void preprotocol()
{
do { } while (wait(id)) ;
flag[id] = true ;
}
private void postprotocol()
{
flag[id] = false ;
}
public void run()
{
for (int i = 0 ; i < N ; i++) flag[i] = false ;
do { noncritical() ;
preprotocol() ;
critical() ;
postprotocol() ; } while (true) ;
}
public static void main(String [ ] args)
{
System.out.println("Busy waiting example 2:") ;
Thread process[] = new mutex2[N] ;
for (int i = 0 ; i < N ; i++)
{
process[i] = new mutex2(i) ;
process[i].start() ;
}
}
}
Although the test run test2 looks safe we can
prove otherwise.