不与“ -lpthread”链接时,为什么pthread_cond_wait()不阻塞?

掷石

我正在学习pthread_cond_t并编写了以下旨在永久阻止的代码pthread_cond_wait()

// main.cpp
// Intentionally blocks forever.

#include <iostream>
#include <cstring>
#include <cerrno>
#include <pthread.h>

int main( int argc, char* argv[] )
{
  pthread_cond_t cond;

  if ( pthread_cond_init( &cond, NULL ) )
  {
    std::cout << "pthread_cond_init() failed: " << errno << "(" << strerror( errno ) << ")" << std::endl;
  }

  pthread_mutex_t mutex;

  if ( pthread_mutex_init( &mutex, NULL ) )
  {
    std::cout << "pthread_mutex_init() failed: " << errno << "(" << strerror( errno ) << ")" << std::endl;
  }

  pthread_mutex_lock( &mutex );
  pthread_cond_wait( &cond, &mutex );

  pthread_cond_destroy( &cond );
  return 0;
}

当我第一次编译/执行该程序时,可执行文件没有挂起-它退出了:

>g++ --version
g++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-7)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

>g++ -g main.cpp && ./a.out 
> // <-- Note: returned to bash prompt

接下来我想链接到的libpthread-而现在可执行雄,符合市场预期:

>g++ -g main.cpp -lpthread && ./a.out 
^C
> // <-- Needed to send SIGINT to terminate process

我实际上期望遇到必需pthread功能的链接错误当我未明确链接时,为什么没有遇到一个libpthread

上面的答案可能使这个问题没有意义,但是当编译时没有显式链接时libpthread,为什么生成的二进制文件“跳过”或忽略了pthead_cond_wait()glibc或某处的pthread函数是否有默认的不执行实现?

PSkocik

当您的进程是多线程时,某些glibc函数需要锁定。为了避免每次都拖入libpthread依赖项,glibc使用weakrefs来引用一堆pthread功能。如果它检测到该功能不可用(由于weakref解决方案而不会导致链接器错误),它将默认将这些操作设置为无操作(这很好,因为如果您没有pthread,则无法是多线程的,则不需要锁定)。该解决方案的结果就是您得到的行为。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

鸟为什么不与壁架碰撞?

为什么块不与球碰撞

Django 静态文件(CSS)不与模板链接

当varargs开始不与no-arg冲突时?

为什么 hitTest(_:with:) 不与以编程方式添加的 UIImageView 交互

为什么它不与计算器错误终止

为什么我的ArrayList不与JAXB一起编组?

.join()为什么不与函数参数一起使用?

为什么小数不与浮点数互操作

为什么{{partial}}不与{{outlet}}共享控制器

为什么using指令不与普通函数“关联”?

Evince为什么不与Ubuntu 13.10中的HUD集成?

为什么xs:any不与jaxb类自动绑定?

为什么索引不与子查询一起使用

sed的s / a * //为什么不与所有a匹配?

React:为什么元素样式不与 setState 切换?

绑定为什么不与转场一起使用

为什么:: after和:: pseudo不与main元素对齐?

为什么熊猫比较运算符不与索引对齐?

为什么我的测验不与 mysql 数据库交互?

如何创建循环(水平不与参考重叠时)

键盘显示时如何使按钮不与EditText重叠?

为什么在pthread_cond_wait之前需要条件检查

为什么pthread_cond_wait有虚假的唤醒?

在 pthread_cond_wait() 中,为什么它在调用者睡眠时解锁互斥锁?

当 flex grow 为 1 时,为什么 flex 子项不与文本内容共享相同的宽度

为什么不与对象,而不是阵列中使用时`键()`函数触发警告或错误?

为什么带有git'squash and merge'选项的PR似乎不与master合并?

我如何找出两个对象为什么不与angular.equals比较?