Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_join on two infinite loop threads?

Tags:

c

posix

pthreads

I just read here that when the main loop ends, any threads that have or have not had a chance to spawn are terminated. So I need to do a join on each thread to wait for it to return.

My problem is, how will I write a program in which I create 2 threads that run in an infinite loop? If I wait to join on an infinite thread, the second one will never get a chance to be created!

like image 626
sgarg Avatar asked Feb 23 '23 13:02

sgarg


1 Answers

You can do this with this sequence:

pthread_create thread1
pthread_create thread2
pthread_join thread1
pthread_join thread2

In other words, start all your threads before you try to join any of them. In more detail, you can start with something like the following program:

#include <stdio.h>
#include <pthread.h>

void *myFunc (void *id) {
    printf ("thread %p\n", id);
    return id;
}

int main (void) {
    pthread_t tid[3];
    int tididx;
    void *retval;

    // Try for all threads, accept less.

    for (tididx = 0; tididx < sizeof(tid) / sizeof(*tid); tididx++)
        if (pthread_create (&tid[tididx], NULL, &myFunc, &tid[tididx]) != 0)
            break;

    // Not starting any is pretty serious.

    if (tididx == 0)
        return -1;

    // Join to all threads that were created.

    while (tididx > 0) {
        pthread_join (tid[--tididx], &retval);
        printf ("main %p\n", retval);
    }

    return 0;
}

This will try to start three threads before joining on any, and then it will join to all those that it managed to get going, in reverse order. The output, as expected, is:

thread 0x28cce4
thread 0x28cce8
thread 0x28ccec
main 0x28ccec
main 0x28cce8
main 0x28cce4
like image 124
paxdiablo Avatar answered Mar 03 '23 14:03

paxdiablo