I need to know if some thread already terminated (if it's not, I must wait for it).
If I call pthread_join()
on terminated thread, it always returns success in my version of glibc.
But documentation for pthread_join()
says that it must return error with code ESRCH
if thread already terminated.
If I call pthread_kill(thread_id, 0)
it returns with error code ESRCH
(as expected).
Inside glibc sources I see that inside pthread_join()
there is simple checking for valid thread_id, but not real checking if thread exist.
And inside pthread_kill()
there is real checking (in some kernel's list).
There is my test program:
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void * thread_func(void *arg)
{
printf("Hello! I`m thread_func!\nGood-bye!\n");
return NULL;
}
int main(void)
{
int res;
pthread_t thread_id;
printf("Hello from main()!\n");
pthread_create(&thread_id, NULL, thread_func, NULL);
printf("Waiting...\n");
sleep(3);
res = pthread_join(thread_id, NULL);
printf("pthread_join() returned %d (%s)\n", res, strerror(res));
res = pthread_kill(thread_id, 0);
printf("pthread_kill() returned %d (%s)\n", res, strerror(res));
return 0;
}
It's output:
Hello! Waiting... Hello! I`m thread_func! Good-bye! pthread_join() returned 0 (Success) pthread_kill() returned 3 (No such process)
My question: is it safe to use pthread_join() to check for terminated threads or I must always use pthread_kill()?