java - Using an array of 3 PetersonLocks to synchronize 4 processes -


assuming have class petersonlock below:

class petersonlock {      atomicboolean flag[] = new atomicboolean[2];      volatile int victim;       public void acquire(int id) {           flag[id].set(true);          victim = id;          while (flag[1-id].get() && victim == id);     }      public void release(int id) {          flag[id].set(false);     } } 

where id either 1 or 0. have following class hierarchically use 3 petersonlocks 4 processes.

class lock4pete{      petersonlock[] lock = new petersonlock[3];      public void acquire(int id) {           lock[0].acquire(id/2);          lock[1+id/2].aquire(id%2);     }      public void release(int id) {           lock[1+id/2].release(id%2);          lock[0].release(id/2);     }   } 

where id 0,1,2 or 3.

i don't understand idea behind , don't know how fix code. don't know trying here. why need 3 locks 4 processes , why can every process use lock[0]?

some appreciated. not homework exercise don't understand.

the 4 threads divided 2 bins, each containing 2 threads. id/2 specifies bin thread belongs to, , id%2 specifies index of thread within bin.

let's rewrite code handle id/2 , id%2 separate variables.

class lock4pete {      // lock determines active bin.     petersonlock masterlock = new petersonlock;      // each of these locks guards corresponding bin.     petersonlock[] binlocks = new petersonlock[2];      public void acquire(int bin, int index) {         // after line executed in 1 of threads,          // thread *different* bin have wait          // until thread calls masterlock.release(bin);           // before can execute masterlock.acquire(another_bin);         masterlock.acquire(bin);          // possible more 1 thread reaches point          // simultaneously, guaranteed same bin.         // need make sure threads bin can          // neither acquire lock simultaneously nor come deadlock.          // after line executed,          // thread *same* bin have wait until          // thread calls binlocks[bin].release(index);          // before can execute binlocks[bin].aquire(another_index);         binlocks[bin].aquire(index);          // thus, 1 thread @ time can reach end of         // method , acquire lock.     }      public void release(int bin, int index) {          binlocks[bin].release(index);          masterlock.release(bin);     } } 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -