Why doesn't the shared static variable update in the threads?

60 views Asked by At

I am trying Peterson's Solution for the Critical Section Problem, and I noticed that my static variable doesn't update unless I add a System.out.print(""); statement.

Why is this so?

Thanks.

The code for Peterson.java is below:

public class Peterson {
    public static void main(String[] args) throws InterruptedException {
        Process p1 = new Process(0);
        Process p2 = new Process(1);
        p1.start();
        p2.start();
        p1.join();
        p2.join();
    }
}

class Process extends Thread {
    static int turn;
    static boolean[] wait = new boolean[2];

    int ind;
    public Process(int ind) {
        this.ind = ind;
    }

    @Override
    public void run() {
        int ind2 = 1-ind;
        wait[ind] = true;
        turn = ind2;
        
        // USING THIS WORKS
        // while(wait[ind2] && turn == ind2) {System.out.print("");}
        // USING THIS DOESN'T WORK
        while(wait[ind2] && turn == ind2) {;}

        // Critical Section
        System.out.printf("%d Started%n", ind);
        for (long t = System.currentTimeMillis(); System.currentTimeMillis() - t < 100;);
        System.out.printf("%d Ended%n", ind);

        wait[ind] = false;
    }
}
0

There are 0 answers