简体   繁体   English

为什么没有lpthread标志的gcc链接?

[英]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. 但是,当我在没有-lpthread标志的情况下编译时,不仅程序仍然可以编译和链接,它还可以在没有死锁的情况下运行。 Why? 为什么?

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

Compiling with the -lpthread flag yields the expected result: 使用-lpthread标志进行编译会产生预期结果:

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

I'm running GCC version 7.2.0. 我正在运行GCC 7.2.0版。

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. 首先,使用PTHREAD_MUTEX_RECURSIVE启动互斥锁,这将允许对互斥锁进行双重锁定 - 管理引用计数,并且仅当引用计数为0时才释放互斥锁。这意味着可以在同一个线程中多次锁定相同的互斥锁,但为了释放它,必须提供相同数量的解锁。

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. 第二个是,此版本中的gcc仅为pthread函数实现存根 - 这意味着如果不添加-lpthread库链接指令,则不会实现锁定函数。 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. 我将尝试通过GCC源代码来验证这确实是第二个选项的结果 - 将添加更新。

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. 注意:始终建议专门链接库,因为它允许控制结果 - GCC内部支持的回退可能导致意外行为,如上所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM