【问题标题】:Why doesn't this_thread::sleep_for need to be linked against pthread?为什么 this_thread::sleep_for 不需要与 pthread 链接?
【发布时间】:2022-01-07 15:19:08
【问题描述】:

通常在 GCC 中构建线程相关代码时,需要针对 pthread 进行显式链接:

g++ -pthread main.cxx

但是,以下代码在不与 pthread 链接的情况下可以正常编译、链接和运行:

#include <iostream>
#include <thread>

using namespace std::chrono_literals;

int main() {
    std::this_thread::sleep_for(1000ms);
    return 0;
}

我猜这里发生的事情是std::this_thread::sleep_for 正在使用来自 libc 的一些 POSIX 函数(而不是来自 pthread 的东西)?但如果是这样的话,std::this_thread::sleep_for 的执行是否会根据是否从主线程调用而改变?

【问题讨论】:

  • 因为 C++11 线程是该语言的一部分,并且为您处理与操作系统的任何交互(从那以后我没有使用 pthread 或操作系统特定的 API 进行线程处理)。 sleep_for 将始终挂起调用它的线程。因此,您来自 main 的调用将暂停主线程 1 秒钟。 (附带说明:如果您想使用 C++ 中的线程,请查看 std::async)
  • 参见stackoverflow.com/questions/70414930/…中的“为什么 glibc 2.34 删除了 libpthread”
  • @PepijnKramer -- 问题是关于在使用 C++ 线程时必须(必须?)显式链接到 pthreads 库的 g++ 怪癖。
  • @PeteBecker 抱歉,我不知道这个怪癖。 (主要使用 msvc 编译器)

标签: c++ multithreading pthreads sleep


【解决方案1】:

为什么 this_thread::sleep_for 不需要与 pthread 链接?

因为对std::this_thread::sleep_for 的调用转换为对nanosleep 的底层调用,它在libc.so.6 中定义,而不是在libpthread.so.0 中。

请注意,当与 GLIBC-2.34 及更高版本链接时,使用其他功能(以前需要 -pthread)不再需要它,因为 GLIBC got rid of libpthread

另见this answer

【讨论】:

  • -pthread 选项不仅仅是链接libpthread(否则-lpthread 就足够了)。我尚不清楚 glibc 删除单独的 libpthread 是否会与 GCC 弃用其 -pthread 选项相匹配。最新的 (11.2) GCC 手册并没有弃用它,而且它长期以来一直被记录为预处理选项和链接器选项。
猜你喜欢
  • 1970-01-01
  • 2020-10-15
  • 2018-09-07
  • 2011-05-25
  • 1970-01-01
  • 2020-09-18
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多