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 番目のフェーズは「クリティカル領域でスレッドを一緒に実行する」ためのものです。私の質問は次のとおりです...特定のタイプのスレッドを考慮するためにコードを変更する方法は? たとえば、水素スレッドと酸素スレッドがあり、バリアに水素原子が 2 つと酸素原子が 1 つあるたびに bond() を実行する必要があります。前もって感謝します。