14

Is there a function in pthread library to synchronize threads? Not mutexes, not semaphores, just one call function. It is supposed to lock the threads that get in that point until all the threads reach such function. E.g:

function thread_worker(){
    //hard working

    syncThreads();
    printf("all threads are sync\n");
}

So the printf is called only when all the threads end the hard working.

Frederico Schardong
  • 1,946
  • 6
  • 38
  • 62

1 Answers1

21

The proper way to do this would be with a barrier. pthread supports barriers using pthread_barrier_t. You initialize it with the number of threads that will need to sync up, and then you just use pthread_barrier_wait to make those threads sync up.

Example:

pthread_barrier_t barr;

void thread_worker() {
    // do work
    // now make all the threads sync up
    int res = pthread_barrier_wait(&barr);
    if(res == PTHREAD_BARRIER_SERIAL_THREAD) {
        // this is the unique "serial thread"; you can e.g. combine some results here
    } else if(res != 0) {
        // error occurred
    } else {
        // non-serial thread released
    }
}


int main() {
    int nthreads = 5;
    pthread_barrier_init(&barr, NULL, nthreads);

    int i;
    for(i=0; i<nthreads; i++) {
        // create threads
    }
}
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • can the same barrier be reused? I need two synchronization points in my threads – Frederico Schardong Oct 16 '12 at 18:55
  • Yep. You can reuse the barrier as long as the number of threads needing synchronization doesn't change. – nneonneo Oct 16 '12 at 19:04
  • yes it's always the same... do I have to destroy and create the barrier again? – Frederico Schardong Oct 16 '12 at 19:07
  • 4
    Like I said, you can reuse the barrier. From `man pthread_barrier_wait`: '[when `pthread_barrier_wait` returns], the barrier shall be reset to the state it had as a result of the most recent pthread_barrier_init() function that referenced it.' – nneonneo Oct 16 '12 at 19:24