为什么gcc链接没有lpthread标志? [英] Why does gcc link without the lpthread flag?

查看:182
本文介绍了为什么gcc链接没有lpthread标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个嗜好项目,其中互斥体的行为神秘。我把它解释成这个测试案例,显然应该是僵局。

  #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\\\
);
返回0;
}

然而,当我编译时没有 -lpthread 标志,不仅程序仍然编译和链接,它也运行而不会发生死锁。为什么呢?



  GCC pthread_break.c -o pthread_test 
./pthread_test
注意到锁两次

使用 -lpthread 标志进行编译会产生预期的结果:

  GCC pthread_break.c -o pthread_test -lpthread 
./pthread_test
将 - 这里$僵持b $ b

我正在运行GCC版本7.2.0。

解决方案

这个问题似乎缺乏信息 - 但它似乎有两个选择:

'p>首先,互斥与 PTHREAD_MUTEX_RECURSIVE 这将允许互斥的决斗锁定启动 - 一个ref计数管理和互斥仅释放时裁判计数为0.这意味着可以在同一个线程中多次锁定相同的互斥锁,但为了释放它,必须提供相同数量的解除锁定。



<第二,这个版本中的gcc只为 pthread 函数实现了存根 - 这意味着如果你不添加 -lpthread 库链接指令锁定功能没有实现。这是由你添加选项后,出现死锁的事实支持的。



我会尝试检查GCC源以验证这确实是一个结果第二个选项 - 将添加更新。



注意:总是建议特别链接这些库,因为它允许对结果进行控制 - GCC内部支持的退步可以导致意想不到的行为,如上所示。


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.

解决方案

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.

这篇关于为什么gcc链接没有lpthread标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆