1
votes

Below is the program for which am expecting the program to go in 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)

Can you help me understand, why pthread_join() unblocks? Because main thread is yet to get terminate and probably this should be a deadlock?

#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
1
this exercise is part of my syllabus - overexchange
Instead of printf("pthread_join(): %d",s); do {errno = s; perror("pthread_join()");} and you might receive enlightning information. - alk

1 Answers

2
votes

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
}