次の方法に従って、C で n 個のスレッドを同期するモニターを作成します。各スレッドは、barrier_synch() メソッドを呼び出します。このメソッドを呼び出す最初の n-1 スレッドはスリープします。n 番目のスレッドがこのメソッドを呼び出すと、スリープ中のすべてのスレッドが起動し、すべてのスレッドが実行を継続しますが、バリアは初期状態に戻ります。これは私が見つけた解決策です:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct barrier{
int n, count;
pthread_mutex_t mutex;
pthread_cond_t cond;
int blocked;
}barrier;
void barrier_init(barrier *bar, int n){
bar->n = n;
bar->count = 0;
pthread_mutex_init(&bar->mutex, NULL);
pthread_cond_init(&bar->cond, NULL);
bar->blocked = 1;
}
void barrier_synch(barrier *bar){
while(1){
pthread_mutex_lock(&bar->mutex);
if (bar->blocked == 1) break;
pthread_mutex_unlock(&bar->mutex);
}
bar->count++;
if(bar->count == bar->n){
bar->blocked = 0;
pthread_cond_broadcast(&bar->cond);
}
while(bar->blocked == 1){
pthread_cond_wait(&bar->cond, &bar->mutex);
}
bar->count--;
if(bar->count == 0){
bar->blocked = 1;
}
pthread_mutex_unlock(&bar->mutex);
}
このコードは正しいですか? 誰かがこのメカニズムがどのように機能するかを簡単な言葉で説明できますか?