Search code examples
cmultithreadingpthreadsmutexbarrier

Thread Barrier synchronization


I want to implement a Barrier synchronization technique on threads

So far I've come up with some code, but I have some questions..

    struct _ThreadBarrier {

    pthread_cond_t cond;
    int needed;
    int waiting;
    int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex); 
    pthread_mutex_t mut;
}


some other code for initilization etc ..




void enterBarrier(ThreadBarrier *barrier) {
    pthread_mutex_lock(&barrier->mut);


    waiting ++;
    if (waiting == needed){

            barrier->cond = 1;
            barrier->waiting = 0;
            pthread_cond_broadcast(&barrier->cond);


   }else{
           barrier->cond = 0;
           pthread_cond_wait&barrier->cond,&barrier->mut); 
   }



   pthread_mutex_unlock(&barrier->mult);

   }

And so I have some questons on the mutex. I am sure that on entering the func. enterBarrier I must lock the mutex, so that no other thread gets it and alters and the same time "waiting"! But I unlock the mutex and the end of the code and I am not sure if other threads ever will go in enterBarrier, because of the locked mutex.

I am not entirely sure how exactly this mutex works.


Solution

  • Here's how it should be. To lock/unlock the condition variable, function are needed. The mutex should be locked in the beginning

    void enterBarrier(ThreadBarrier *barrier) {
    pthread_mutex_lock(&barrier->mut);
    
    
    barrier->waiting ++;
    
    if (barrier->waiting == barrier->needed){
    
        barrier->waiting = 0;
        pthread_cond_broadcast(&barrier->cond);
    
    }else{
        pthread_cond_wait(&barrier->cond,&barrier->mut); 
    
    }
    
    pthread_mutex_unlock(&barrier->mut);
    

    }