使用3个PetersonLocks数组来同步4个进程

时间:2017-08-21 07:10:00

标签: java multithreading concurrency synchronization locking

假设我们有类PetersonLock,如下所示:

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);
    }
}

其中id是1或0.我现在有以下类来分层使用3个PetersonLocks进行4个进程。

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);
    }
  }

id为0,1,2或3时。

我不明白这背后的想法,我也不知道如何修复此代码。我不知道他们在这里要做什么。为什么我们需要为4个进程提供3个锁,为什么每个进程都使用lock [0]?

一些帮助将非常感激。这不是家庭作业,而是我不太懂的练习。

1 个答案:

答案 0 :(得分:1)

4个线程分为2个分区,每个分区包含2个线程。 id/2指定线程所属的bin,id%2指定其bin中线程的索引。

让我们重写代码以将id/2id%2作为单独的变量处理。

class Lock4Pete {

    // This lock determines the active bin.
    PetersonLock masterLock = new PetersonLock;

    // Each of these locks guards the corresponding bin.
    PetersonLock[] binLocks = new PetersonLock[2];

    public void Acquire(int bin, int index) {
        // After this line is executed in one of the threads, 
        // any thread from a *different* bin will have to wait 
        // until this thread calls masterLock.Release(bin);  
        // before it can execute masterLock.Acquire(another_bin);
        masterLock.Acquire(bin);

        // It is possible that more than one thread reaches this point 
        // simultaneously, but they are guaranteed to be from the same bin.
        // Now we only need to make sure that threads from that bin can 
        // neither acquire the lock simultaneously nor come to a deadlock.

        // After this line is executed, 
        // any thread from the *same* bin will have to wait until 
        // this thread calls binLocks[bin].Release(index); 
        // before it can execute binLocks[bin].Aquire(another_index);
        binLocks[bin].Aquire(index);

        // Thus, only one thread at a time can reach the end of this
        // method and acquire the lock.
    }

    public void Release(int bin, int index) {
         binLocks[bin].Release(index);
         masterLock.Release(bin);
    }
}