Search code examples
cmultithreadingpthreadspthread-joinpthread-barriers

How to make all threads (pthread) wait till rest of all other threads are running before starting its execution?


The main processes launches 4 threads. Now at this time all 4 threads will start execution immediately, but I want all the threads to wait till rest of all threads are also in running state.

I remember using a semaphore to track the thread counts, but not able to recall it. Is there any simple way to do without doing any busy-wait?

void *thread_routine(void *arg)
{
    // this thread should wait here till rest of all threads are also ready to run

    // do some job here

    return NULL;
}

int main(int argc, char *argv[])
{
    int i = 0;
    pthread_t thid[4];

    for (i = 0; i < 4; i++) {
        pthread_create(&tid[i], NULL, thread_routine, NULL);
    }

    for (i = 0; i < 4; i++) {
       pthread_join(tid[i], NULL);
    }
    return 0;
}

Solution

  • What you describe sounds like barrier synchronization which can be implemented using pthread_barrier_wait.

    Here's a simple example using it (from TLPI book).