質問

I want to make a monitor that synchronizes n threads in C according to the following way: Each thread calls barrier_synch() method. First n-1 threads that call this method sleep. When the n-th thread calls this method, all sleeping threads wake up and then all threads continue the execution, while the barrier returns to the initial condition. This is a solution I found:

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

Is this code correct? Can somebody explain me in simple words how this mechanism works?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top