Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

c - Pthread Run a thread right after it's creation

I have a C program in which I use pthread.

I would like newly created threads to run as soon as they are created.

The reason behind this is that my threads have initialisation code to set up signal handlers, and I must be sure the handlers are ready, before my main thread sends some signals.

I've tried doing pthread_yield just after my pthread_create, but without success.

I doubt it makes a difference, but I am running Linux 3.6 on x86_64.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
");

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

    printf("main: children finished
");

    /* 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
");
    pthread_barrier_wait(b);
    printf("child: after
");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...