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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With