簡體   English   中英

為什么pthread_cond_wait()在沒有與“-lpthread”鏈接時不會阻塞?

[英]Why does pthread_cond_wait() not block when not linked with “-lpthread”?

我正在學習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函數是否有一些默認的do-nothing實現?

當您的進程是多線程時,某些glibc函數需要鎖定。 為了避免每次因為libpthread依賴性而拖拽,glibc使用weakrefs來引用一堆pthread功能。 如果它檢測到功能不可用(由於weakref解決方案不會導致鏈接器錯誤),它會將這些操作默認為no-ops(這很好,因為如果你沒有pthread,你就不能多線程並且不需要鎖定)。 這個解決方案的結果就是你得到的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM