In the following program, what are the possibilities for the ordering of threads? Assuming "function" will print thread id which is unique (since here we have only one process). I always get the order th1,th2!
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
int main()
{
pthread_t th1;
pthread_t th2;
pthread_create(&th1, NULL, function, NULL);
pthread_create(&th2, NULL, function, NULL);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
}
return 0;
}
The only ordering guarantees here are that pthread_join(th1, NULL);
will not return until thread 1 has exited and pthread_join(th2, NULL);
will not return until thread 2 has exited. Consequently, the main()
function will not return (and the process will not exit) until both thread 1 and thread 2 have exited.
There is no ordering imposed between thread 1 and thread 2 - their execution can be arbitrarily interleaved.