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