1

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

paul
  • 1,212
  • 11
  • 15
  • 1
    AFAIK guaranteeing a thread will run at any given time is impossible, because the OS scheduler has the ultimate decisions in those matters. You can only tell it to put it in the scheduler queue and it will run at a given point, for a quantum slice or more. – Tony The Lion Sep 21 '12 at 19:06
  • I do not want to set at what time my thread will run, but pause the main thread until my initialisation code in the other thread has run. – paul Sep 21 '12 at 19:12
  • "I would like newly created threads to run as soon as they are created." AFAIK that says you want to run the threads as soon as they are created. IF you want to know how to pause a thread waiting for another or others, then ask that. – Tony The Lion Sep 21 '12 at 19:14
  • Are these threads meant to complete? Or do they set handlers, then wait for signals? – user7116 Sep 21 '12 at 19:26
  • 1
    Possible duplicate of [pthread execution on linux](https://stackoverflow.com/q/4991470/608639) – jww Aug 14 '19 at 12:49

2 Answers2

6

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");
}
user7116
  • 63,008
  • 17
  • 141
  • 172
5

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.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547