Below is the program for which I am expecting the program to go into a deadlock because pthread_join() is a blocking wait on a thread (it is waiting to terminate).
But I see that pthread_join() does not block and returns with failure (35 = EDEADLK)
Can you help me understand why pthread_join() unblocks? Because the main thread is yet to terminate and probably this should be a deadlock?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int
main(int argc, char *argv[])
{
void *res;
int s;
printf("Message from main()\n");
s = pthread_join(pthread_self(), &res);
if (s != 0)
printf("pthread_join(): %d",s);
printf("Thread returned %d\n", (int) res);
exit(0);
}
Here is the output:
Message from main()
pthread_join(): 35
Thread returned 134514009
You cannot join to yourself. The POSIX manpage for pthread_join
specifies that you may get a deadlock error:
[EDEADLK]
A deadlock was detected or the value of thread specifies the calling thread.
And, indeed, a search of that error shows that it's 35
, at least on my system:
pax> cd /usr/include
pax> grep EDEADLK *.h */*.h */*/*.h
asm-generic/errno.h:#define EDEADLK 35 /* Resource deadlock would occur */
While some deadlocks are subtle and difficult for pthreads to automatically detect, this one is relatively easy, with something like this at the start of the join function:
int pthread_join(pthread_t thread, void **value_ptr) {
if (thread == pthread_self())
return EDEADLK;
// rest of function
}