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 trying 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 someone, and then join all those with which he managed to switch in the reverse order. The conclusion, as expected, is as follows:
thread 0x28cce4 thread 0x28cce8 thread 0x28ccec main 0x28ccec main 0x28cce8 main 0x28cce4
source share