1

我想根据以下方式制作一个同步C中n个线程的监视器:每个线程调用barrier_synch()方法。调用此方法的前 n-1 个线程休眠。当第n个线程调用该方法时,所有休眠线程都被唤醒,然后所有线程继续执行,而barrier返回初始状态。这是我找到的解决方案:

#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);
}

这段代码正确吗?有人能用简单的话解释一下这个机制是如何工作的吗?

4

1 回答 1

0

Check out The Little Book of Semaphores for all sorts of synchronization primitives and uses. It isn't in C, but it should help you in thinking about your code in a structured, correct way.

于 2014-01-24T18:39:20.343 回答