Barrier implementation with mutex and condition variable

Posted by kkp on Programmers See other posts from Programmers or by kkp
Published on 2012-06-10T19:06:20Z Indexed on 2012/06/10 22:46 UTC
Read the original article Hit count: 212

I would like to implement a barrier using mutex locks and conditional variables. Please let me know whether my implementation below is fine or not?

static int counter = 0;
static int Gen = 999;

void* 
thread_run(void*) 
{
      pthread_mutex_lock(&lock);
        int g = Gen;
        if (++counter == nThreads) {
            counter = 0;
            Gen++;
            pthread_cond_broadcast(&cond_var);
        } else {
             while (Gen == g) 
                 pthread_cond_wait(&cond_var, &lock);
        }
        pthread_mutex_unlock(&lock);

     return NULL;
}

© Programmers or respective owner

Related posts about multithreading

Related posts about synchronization