我想创建一个监视器,根据以下方式同步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);
}
这段代码是否正确?有人能用简单的话解释我这个机制是如何运作的吗?