Hi Everyone,
This is an interesting problem that I am not able to find documentation for why this may be the case. I am teaching a course in Operating Systems (a typical junior-level course in CS departments). I asked by students to implement a semaphore class in Java using Peterson's algorithm for synchronization. I was toying around with a solution that I wrote, and noticed that if I take out one of the printf calls that I was using to demonstrate what is happening that sometimes a thread will hang in the P() method of the MySemaphore class. When the printf is in there is no problem, it works properly each time. My first thought was that the printf caused an i/o interrupt that provides an opportunity for the thread to yield and the other thread is able to execute. However, this does not ring true to me. So I am thinking that I missed something, and need another set of eyes on this. Take a look and let me know what you see.
I uploaded all of the source files here, but this is a copy of the MySemaphore class and someone may be able to spot my problem here. There is a comment before the printf in the while (value < 0) loop of the P(int) method that shows you which line can be commented out to reproduce the hanging, if that line is not commented out it seems to work fine.
Thanks for your help
public class MySemaphore { private int value; private int favoredThread; private boolean tWantsToEnter[] = new boolean[2]; private String name; public MySemaphore(int v, String n) { value = v; // initial state favoredThread = 1; tWantsToEnter[0] = false; tWantsToEnter[1] = false; name = n; } public void V(int thread) { value++; System.out.printf("Thread %d is in %s.V() value = %d\n", thread, name, value); // signal to waiting threads tWantsToEnter[thread] = false; } public void P(int thread) { int otherThread = (thread == 0) ? 1 : 0; value--; System.out.printf("Thread %d is in %s.P() value = %d\n", thread, name, value); tWantsToEnter[thread] = true; favoredThread = otherThread; while (tWantsToEnter[otherThread] && favoredThread == otherThread) System.out.printf("Thread %d is busy-waiting\n",thread); while (value < 0) { // wait [B][COLOR="Red"] // when this line is in, all is well. When it's out. One of the threads hangs here forever! [/COLOR][/B] System.out.printf("Thread %d is busy-waiting value:%d < 0\n",thread, value); while (tWantsToEnter[otherThread] && favoredThread == otherThread) System.out.printf("Thread %d is busy-waiting\n",thread); } } }