为什么在 GCC 和 Clang 中使用 std::thread 需要 -pthread?
Why is -pthread necessary for usage of std::thread in GCC and Clang?
为什么编译直接或间接使用std::thread
的程序时指定-std=c++11
并不意味着-pthread
? std::thread
在幕后使用 pthreads 的实现细节暴露给程序员,这似乎很奇怪;如果要让用户选择 posix 兼容的线程库,为什么不默认使用 pthreads 并使用一些 --threading-model=<your_favorite_posix_threads_library>
参数来覆盖它?
-pthread
选项并非普遍需要使用 std::thread
- 这是您正在构建的任何平台的实现怪癖。
正在编译:
#include <thread>
#include <iostream>
int main()
{
std::thread t{[]()
{
std::cout << "Hello World\n";
}};
t.join();
return 0;
}
与
clang -std=c++11 ThreadTest.cpp -lc++
在 MacOSX 上,构建并运行,如果我们这样做:
otool -L a.out
a.out:
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.0.0)
我们可以看到,我们不需要 link 任何额外的东西来完成这项工作 - 它也没有在幕后发生。 pthreads 是一个单独的库,这似乎是一个平台实现细节。
选择具有 pthread 接口的线程库是 *NIX 系统上的遗留包袱,其中许多系统开始时没有线程支持,然后在拥有完整内核之前经历了用户-space 线程阶段支持。我想它仍然存在,因为没有人喜欢进行重大更改。
为什么编译直接或间接使用std::thread
的程序时指定-std=c++11
并不意味着-pthread
? std::thread
在幕后使用 pthreads 的实现细节暴露给程序员,这似乎很奇怪;如果要让用户选择 posix 兼容的线程库,为什么不默认使用 pthreads 并使用一些 --threading-model=<your_favorite_posix_threads_library>
参数来覆盖它?
-pthread
选项并非普遍需要使用 std::thread
- 这是您正在构建的任何平台的实现怪癖。
正在编译:
#include <thread>
#include <iostream>
int main()
{
std::thread t{[]()
{
std::cout << "Hello World\n";
}};
t.join();
return 0;
}
与
clang -std=c++11 ThreadTest.cpp -lc++
在 MacOSX 上,构建并运行,如果我们这样做:
otool -L a.out
a.out:
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.0.0)
我们可以看到,我们不需要 link 任何额外的东西来完成这项工作 - 它也没有在幕后发生。 pthreads 是一个单独的库,这似乎是一个平台实现细节。
选择具有 pthread 接口的线程库是 *NIX 系统上的遗留包袱,其中许多系统开始时没有线程支持,然后在拥有完整内核之前经历了用户-space 线程阶段支持。我想它仍然存在,因为没有人喜欢进行重大更改。