Matthew Hebert
Matthew Hebert

Reputation: 1

Pthread synchronization with barrier

I am trying to synchronize a function I am parallelizing with pthreads.

The issue is, I am having a deadlock because a thread will exit the function while other threads are still waiting for the thread that exited to reach the barrier. I am unsure whether the pthread_barrier structure takes care of this. Here is an example:

static pthread_barrier_t barrier;

static void foo(void* arg) {

  for(int i = beg; i < end; i++) {
 
    if (i > 0) {

      pthread_barrier_wait(&barrier);

    }

  }

}



int main() {

// create pthread barrier

pthread_barrier_init(&barrier, NULL, NUM_THREADS);

// create thread handles

//...

// create threads

  for (int i = 0; i < NUM_THREADS; i++) {

    pthread_create(&thread_handles[i], NULL, &foo, (void*) i);

  }

// join the threads

  for (int i = 0; i < NUM_THREADS; i++) {

    pthread_join(&thread_handles[i], NULL);

  }

}

Here is a solution I tried for foo, but it didn't work (note NUM_THREADS_COPY is a copy of the NUM_THREADS constant, and is decremented whenever a thread reaches the end of the function):

static void foo(void* arg) {

  for(int i = beg; i < end; i++) {

    if (i > 0) {

      pthread_barrier_wait(&barrier);

    }

  }

  pthread_barrier_init(&barrier, NULL, --NUM_THREADS_COPY);

}

Is there a solution to updating the number of threads to wait in a barrier for when a thread exits a function?

Upvotes: 0

Views: 1818

Answers (1)

John Bollinger
John Bollinger

Reputation: 180351

You need to decide how many threads it will take to pass the barrier before any threads arrive at it. Undefined behavior results from re-initializing the barrier while there are threads waiting at it. Among the plausible manifestations are that some of the waiting threads are prematurely released or that some of the waiting threads never get released, but those are by no means the only unwanted things that could happen. In any case ...

Is there a solution to updating the number of threads to wait in a barrier for when a thread exits a function?

... no, pthreads barriers do not support that.

Since a barrier seems not to be flexible enough for your needs, you probably want to fall back to the general-purpose thread synchronization object: a condition variable (used together with a mutex and some kind of shared variable).

Upvotes: 1

Related Questions