I would like to solve mutual exclusion using the Swap function but the program suffer from deadlock and I don't know why. It seems the problem occur when a thread exec two consecutive times.
The swap lock logic:
Every thread make use of a local variable and a shared variable. A thread at first lock its local variable (e.g. assume 1 value). When a thread local variable is unlocked (e.g. assume 0 value) it can execute the critical section, if the thread local variable is locked (e.g. assume 1 value) the thread is in a busy-waiting (the busy waiting tests the local variable unlocking and calls the swap function)
The swap function sets the local variable to the shared variable value and viceversa.The swap function has to be ATOMIC.
When a thread call swap, if the the "shared" variables is 0 (unlock) after swap we have that shared variable is 1 and the local to 0. So only that thread can access to the critical section no others.
At the end (no more critical section) the thread unlock the shared variable.
Main
public class Mutex {
public static void main(String []args){
LockVar var = new LockVar(0);
ThreadSwap th0 = new ThreadSwap(var);
ThreadSwap th1 = new ThreadSwap(var);
ThreadSwap th2 = new ThreadSwap(var);
th0.start();
th1.start();
th2.start();
}
}
Thread Class (The logic of this type of mutex is emphasized)
class ThreadSwap extends Thread{
private LockVar shared_var;
public ThreadSwap(LockVar var){
this.shared_var = var;
}
@Override
public void run(){
LockVar local = new LockVar(1);
while(true){
---> local.setVar(1);
---> while(local.getVar() == 1){Synch.SWAP(shared_var, local);}
System.out.println("Thread " + getId() + " exec critical section.");
// Critical section
System.out.println("Thread " + getId() + " is leaving critical section.");
---> shared_var.setVar(0);
}
}
}
Swap function
class Synch{
public static synchronized void SWAP(LockVar shared, LockVar local){
int temp = shared.getVar();
shared.setVar(local.getVar());
local.setVar(temp);
}
...
}
Shared var Class
class LockVar{
private volatile int var;
public LockVar(int value){
this.var = value;
}
public int getVar(){
return this.var;
}
public void setVar(int value){
this.var=value;
}
}