g ++ - 为什么我必须在使用std :: thread时传递“-pthread”选项?
问题描述:
我只是想了解g ++使用的一个概念。在这里我很简单的std ::跟帖报名:g ++ - 为什么我必须在使用std :: thread时传递“-pthread”选项?
#include <iostream>
#include <thread>
void func() {
std::cout << "Running..." << std::endl;
}
int main()
{
std::thread t(func);
t.join();
return 0;
}
我可以用下面的命令编译它在MacOS/Xcode的9.0设置:
g++ main.cpp -std=c++11
但我无法编译它Linux使用相同的命令,据我所知我也必须通过-pthread
选项。否则,它给了我以下错误:
gcc版本7.1.1 20170622(红帽7.1.1-3)
main.o: In function `std::thread::thread<void (&)()>(void (&)())':
/usr/include/c++/5/thread:137: undefined reference to `pthread_create'
我认为这是不符合逻辑的,我不应该知道,它的实现std :: thread类通过pthread。为什么我必须通过-pthread
选项并链接到pthread库? C++ 11是否应该将我从平台特定的细节中抽象出来?或者我有任何其他的替代库,如pthread,我可以链接到我的std ::线程的用法?或者我应该将其报告为一个错误?
谢谢。
答
pthread
是使用操作系统特定调用的操作系统特定线程的行业标准。
std::thread
是C++中的一个抽象,可以使用pthread
或OS的本机线程来实现。但为了让它在尽可能多的操作系统上运行得更快,std-library
的实施者可以在posix
中实现它,因为它们应该适合所有兼容的操作系统。
也有例外,某些窗口只有std-library
改为使用Windows原生线程。
使用现代版本的GCC,你不需要这样做 - 你的GCC版本是什么? –
C++ 11或任何其他版本不指定您如何与compler/tools进行交互。你只需要接受在某些平台上,当你需要某些特性时,你需要用特定的标志调用编译器。 – nos
@NeilButterworth gcc version 7.1.1 20170622(Red Hat 7.1.1-3) –