Why does gcc link without the lpthread flag?

有些话、适合烂在心里 提交于 2020-01-03 13:58:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/47689280/why-does-gcc-link-without-the-lpthread-flag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!