【发布时间】: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