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


Solution 1:

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

Solution 2:

Or you might use a barrier, i.e. call pthread_barrier_wait (early in the routine of each thread, or at initialization in the main thread), to ensure that every relevant thread has reached the barrier (after which some of your threads could do your naughty signal tricks). See this question.