首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用3个PetersonLocks的数组来同步4个进程

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

Stack Overflow用户
提问于 2017-08-21 15:10:00
回答 1查看 76关注 0票数 1

假设我们有如下的PetersonLock类:

代码语言:javascript
复制
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个进程。

代码语言:javascript
复制
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个锁?为什么每个进程都可以使用锁

如果能得到一些帮助,我们将不胜感激。这不是家庭作业,而是一个我不太理解的练习。

EN

回答 1

Stack Overflow用户

发布于 2017-08-21 19:45:55

这4个线程被分成2个箱,每个箱包含2个线程。id/2指定线程所属的bin,id%2指定线程在bin中的索引。

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

代码语言:javascript
复制
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);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45791189

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档