【问题标题】:Why does pthread_cond_wait() not block when not linked with "-lpthread"?为什么 pthread_cond_wait() 不与“-lpthread”链接时不阻塞?
【发布时间】:2018-12-12 05:58:15
【问题描述】:

我正在了解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 函数是否有一些默认的无操作实现?

【问题讨论】:

  • 我认为我们必须对此进行调查才能找到原因:code.woboq.org/userspace/glibc/nptl/pthread_cond_wait.c.html
  • 这是 C++,不是 C。
  • 使用“strace -f ./a.out”启动并查看发生了什么,或者使用 gdb 进行调试。
  • @ChristianGibbons 这个问题与 C 函数有关。使用此 C 函数的示例代码是用 C++ 编写的,但这不是问题。

标签: c++ c pthreads glibc condition-variable


【解决方案1】:

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

【讨论】:

  • 哇!遇到同样的问题,这救了我的命!
猜你喜欢
  • 2012-10-19
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 2018-05-21
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
相关资源
最近更新 更多