Home > front end >  How to make all threads (pthread) wait till rest of all other threads are running before starting it
How to make all threads (pthread) wait till rest of all other threads are running before starting it

Time:09-05

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;
}

CodePudding user response:

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).

  • Related