使用线程和信号量为java中的特定线程类型实现cyclicbarrier

时间:2013-03-31 01:21:12

标签: java multithreading semaphore cyclicbarrier

public class cyclicBarrier {
    private static int n;
    private static int count;
    private static semaphore mutex;
    private static semaphore turnstile;
    private static semaphore turnstile2;

    public cyclicBarrier(int n){
        this.n = n;
        this.count = 0;
        this.mutex = new semaphore(1);
        this.turnstile = new semaphore(0);
        this.turnstile2 = new semaphore(0);
    }

    public synchronized void down() throws InterruptedException{
        this.phase1();
        this.phase2();
    }

    private synchronized void phase1() throws InterruptedException {
        this.mutex.down();
        this.count++;
        if (this.count == this.n){
            for (int i=0; i< this.n; i++){
                          this.turnstile.signal();
                    }
        }
        this.mutex.signal();
        this.turnstile.down();
    }

    private synchronized void phase2() throws InterruptedException {
        this.mutex.down();
        this.count--;
        if (this.count == 0){
            for (int i=0; i< this.n; i++){
                          this.turnstile2.signal();
                    }
        }
        this.mutex.signal();
        this.turnstile2.down();
    }
}

&安培;&安培;这里是类信号量,以防万一

public class semaphore{
    private int counter;

    public semaphore(int number){
        if (number > 0) {
            this.counter = number;
        }
    }

    public synchronized void signal(){
        this.counter++;
        notifyAll();
    }

    public synchronized void down() throws InterruptedException{
        while (this.counter <= 0){
            wait();
        }
        this.counter--;
    }
}

这是我编写的代码,用于使用线程实现 Cyclicbarriers 。 我从书中获取了伪代码以及关于死锁的注释,所以我认为它非常好“虽然可能存在错误”。第一阶段是“到达线程”,第二阶段是“在关键区域中一起运行线程”。我的问题如下......如何更改代码以便考虑特定类型的线程?例如,有氢线和氧线,我希望它们每次在屏障上有2个氢原子和1个氧原子时执行bond()。先感谢您。

2 个答案:

答案 0 :(得分:0)

你需要自己实施Cyclicbarriers吗? (家庭作业) 或者你可以使用JDK的实现吗? http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html

也许你可以扩展await()方法,包含你的Atom类,并添加一个方法来告诉你在屏障处等待的原子,如果你发现说H20的条件,你可以调用一个回调方法,在这种情况下,债券(原子[]原子)

答案 1 :(得分:0)

我没有给你答案,而是给你一个提示。如果你想要我完整答案,请告诉我。

首先,根据my answer修改代码到your other question - 如果我对其缺陷是正确的,那就是:)

其次,假设我们有 m 线程和 barrier(n),其中m> = 2n,每个线程都在执行

while True:
    noncritical()
    barrier.enter() # e.g. phase1()
    critical()
    barrier.leave() # e.g. phase2()

如果您按照我的建议实施输入()离开(),您可能会在关键部分中包含 2n 个主题。为了解决这个问题,我提出了以下结构:

class N_At_A_Time_Barrier(n):
    fields:
        occupied = Semaphore(n)
        barrier = Barrier(n)
    method enter():
        occupied.down()
        barrier.down()
    method leave():
        occupied.up()

The Little book of Semaphores的术语中,占用是Multiplex。提示:H2O问题的解决方案非常类似于此。我的解决方案使用屏障(1 + 2)和......别的东西:)

(脚注:有更有效的方法来实现 N_At_A_Time_Barrier ,其中每组 n 线程都有自己的共享状态,由第一个线程到达,但这更复杂,我不认为它与H2O问题有关。但