Pthread Run a thread right after it’s creation

If your goal is to have the main thread wait for all threads to reach the same point before continuing onward, I would suggest using pthread_barrier_wait:

void worker(void*);

int main(int argc, char **argv)
{
    pthread_barrier_t b;
    pthread_t children[TCOUNT];
    int child;

    /* +1 for our main thread */
    pthread_barrier_init(&b, NULL, TCOUNT+1);

    for (child = 0; child < TCOUNT; ++child)
    {
        pthread_create(&children[child], NULL, worker, &b);
    }

    printf("main: children created\n");

    /* everybody who calls barrier_wait will wait 
     * until TCOUNT+1 have called it
     */
    pthread_barrier_wait(&b);

    printf("main: children finished\n");

    /* wait for children to finish */
    for (child = 0; child < TCOUNT; ++child)
    {
        pthread_join(&children[child], NULL);
    }

    /* clean-up */
    pthread_barrier_destroy(&b);

    return 0;
}

void worker(void *_b)
{
    pthread_barrier_t *b = (pthread_barrier_t*)_b;
    printf("child: before\n");
    pthread_barrier_wait(b);
    printf("child: after\n");
}

Leave a Comment