Program mutex1
// CS237 - Busy waiting example 1
// ==============================
// First attempt at solving the MEP
// using a `turn' variable' as a baton.
class mutex1 extends Thread
{
static int N = 2 ; // Number of processes.
static int turn = 0 ;
private int id ;
public mutex1(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 void preprotocol()
{
do { } while (turn != id) ;
}
private void postprotocol()
{
turn = random(N) ;
System.out.println("turn = "+turn) ;
}
public void run()
{
do { noncritical() ;
preprotocol() ;
critical() ;
postprotocol() ; } while (true) ;
}
public static void main(String [ ] args)
{
System.out.println("Busy waiting example 1:") ;
Thread process[] = new mutex1[N] ;
for (int i = 0 ; i < N ; i++)
{
process[i] = new mutex1(i) ;
process[i].start() ;
}
}
}