Question

So basically the situation I am in is I have a bunch of threads each doing different calculations throughout the week. At the end of the week, every thread calls function X() and then starts calculating for the next week and repeats this cycle.

However, only one thread is allowed to actually do the operations in method X() and only when all threads have reached method X(). Furthermore, none of the threads can continue on their way until the one thread that got to use method X() is finished.

So I'm having difficulty implementing this. I feel like I need to use a condition variable but I'm still shaky with threads and whatnot.

Was it helpful?

Solution

Barriers are a useful synchronization method here.

In pthreads, you can use two barriers, each initialized to a require however many threads are running. The first synchronizes threads after they've finished calculating, and the second after one of them has called X(). Conveniently, the pthread_barrier_wait will elect one and only one of your N waiting threads to actually call X():

void *my_thread(void *whatever) { // XXX error checking omitted
  while (1) {
    int rc;

    do_intense_calculations();

    // Wait for all calculations to finish
    rc = pthread_barrier_wait(&calc_barrier);

    // Am I nominated to run X() ?
    if (rc == PTHREAD_BARRIER_SERIAL_THREAD) X();

    // Wait for everyone, including whoever is doing X()
    rc = pthread_barrier_wait(&x_barrier);
}

Java's CyclicBarrier with a Runnable argument would let you do the same thing with but one barrier. (The Runnable is run after all parties arrive but before any are released.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top