I'm new to Computer Science and I'm reading a book which introduces threads and mutexes. I've tried programming a mutex in Java which seems to work most of the time but every so often it won't.
In my code, the critical section adds on the numbers 1 to 10 to a static variable j which results in 55 (if j starts at 0). If I run three threads at the same time through the critical section, I get random final values of j which makes sense.
But with the mutex below, most of the time I get a final j value of 165 (55*3) which is what I want but on occasions, I get random values of j. Can someone have a look at my code and see what's going on? Thanks!
public class Mythread extends Thread {
private static int j = 0;
private static int mutex = 0; // Initial value of the mutex is 0;
@Override
public void run() {
while (test_and_set(mutex) == 1) {
// wait here if mutex is 1
System.out.println("Thread waiting..");
}
for (int i = 1; i <= 10; i++) { // Start of Critical section
j += i; //
}
System.out.println(j); // End of Critical section
// Should add on 55 to j if one thread is running through the CS
mutex = 0; // Thread that has finished the CS sets the mutex to 0.
}
public static int test_and_set(int oldMutexValue) {
if (mutex == 0) {
mutex = 1;
}
return oldMutexValue;
}
}
public class Test1 {
public static void main(String[] args) {
Mythread thread1 = new Mythread();
Mythread thread2 = new Mythread();
Mythread thread3 = new Mythread();
thread1.start();
thread2.start();
thread3.start();
}
}