简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM