The pure way to find out if a thread is calling pthread_join()
against that thread.
// int pthread_join(pthread_t thread, void **retval); int retval = 0; int r = pthread_join(that_thread_id, &retval); ... here you know that_thread_id returned ...
The problem with pthread_join()
is that if the thread never returns (continues to work as expected), then you are blocked. Therefore, this is not very useful in your case.
However, you can check if you can join (tryjoin) as follows:
//int pthread_tryjoin_np(pthread_t thread, void **retval); int retval = 0; int r = pthread_tryjoin_np(that_thread_id, &relval); // here 'r' tells you whether the thread returned (joined) or not. if(r == 0) { // that_thread_id is done, create new thread here ... } else if(errno != EBUSY) { // react to "weird" errors... (maybe a perror() at least?) } // else -- thread is still running
There is also a synchronized connection that will wait for a certain amount of time, like a few seconds. Depending on the number of threads to check, and if your main process just sits elsewhere, this might be the solution. Block thread 1 for 5 seconds, then thread 2 for 5 seconds, etc., which will be 5000 seconds per cycle for 1000 threads (about 85 minutes to bypass all threads taking into account the time required to manage things .. .)
The manual page has sample code that shows how to use the pthread_timedjoin_np () function. All you have to do is set up a for loop to check each of your threads.
struct timespec ts; int s; ... if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { } ts.tv_sec += 5; s = pthread_timedjoin_np(thread, NULL, &ts); if (s != 0) { }
If your main process has other things to do, I would suggest that you don't use the temporary version and just go through all the threads as fast as you can.