Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does gcc link without the lpthread flag?

I was working on a hobby project where mutexes were behaving mysteriously. I boiled it down to this test case that should obviously deadlock.

#include <pthread.h>
#include <stdio.h>

int main() {
    pthread_mutex_t test;
    pthread_mutex_init(&test, NULL);
    pthread_mutex_lock(&test);
    pthread_mutex_lock(&test);
    printf("Took lock twice\n");
    return 0;
}

However, when I compile without the -lpthread flag, not only does the program still compile and link, it also runs without deadlocking. Why?

gcc pthread_break.c -o pthread_test  
./pthread_test
Took lock twice

Compiling with the -lpthread flag yields the expected result:

gcc pthread_break.c -o pthread_test -lpthread  
./pthread_test
     <- deadlocked here

I'm running GCC version 7.2.0.

like image 862
Lambert Wang Avatar asked Nov 07 '22 13:11

Lambert Wang


1 Answers

The question seems lacking in info - but it seems that there are two options:

First, the mutex is initiated with PTHREAD_MUTEX_RECURSIVE which will allow duel locking of a mutex - a ref count is managed and the mutex is only freed when the ref count is 0. this means that one can lock the same mutex several times in the same thread, but in order to free it one must provide the same amount of un-locks.

The second, is that the gcc in this version only implements stubs for the pthread functions - which means that if you do not add the -lpthread library linking directive the lock functions are not implemented. this is supported by the fact that after you did add the option, the deadlock appears.

I will try and go over the GCC source to verify that this is indeed a result of the second option - will add an update.

NOTE: It is always recommended to link the libraries specifically since it allows control over the outcome - fallback on GCC internal support can cause unexpected behaviour, as seen above.

like image 106
Omer Dagan Avatar answered Nov 15 '22 07:11

Omer Dagan