g ++-为什么我必须通过"-pthread"使用std :: thread时的选项? [英] g++ - Why do I have to pass "-pthread" option while using std::thread?

查看:137
本文介绍了g ++-为什么我必须通过"-pthread"使用std :: thread时的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想了解g ++使用的一个概念.这是我非常简单的std :: thread应用程序:

I'm just trying to understand a concept used by g++. Here my very simple std::thread application:

#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安装程序上对其进行编译:

I'm able to compile it on macOs/Xcode 9.0 setup with following command:

g ++ main.cpp -std = c ++ 11

g++ main.cpp -std=c++11

但是据我所知,我也必须通过 -pthread 选项,因此我无法使用相同的命令在Linux上进行编译.否则会给我以下错误:

But I'm unable to compile it on Linux with the same command, as far as I know I have to pass -pthread option too. Otherwise it gives me following error:

gcc版本7.1.1 20170622(Red Hat 7.1.1-3)

main.o: In function `std::thread::thread<void (&)()>(void (&)())':
/usr/include/c++/5/thread:137: undefined reference to `pthread_create'

我认为这是不合逻辑的,我什至不知道它通过pthread实现了std :: thread类.为什么我必须传递 -pthread 选项并链接到pthread库?C ++ 11是否不应该使我脱离平台特定的细节?还是我可以为我的std :: thread使用链接到其他替代库(例如pthread)?还是应该将其报告为错误?

I think it's illogical and I shouldn't even know that it's implementing the std::thread class via pthread. Why do I have to pass -pthread option and link against pthread library? Isn't C++11 supposed to abstract me away from platform specific details? Or do I have any other alternative libraries such as pthread that I can link against for my std::thread usage? Or should I report that as a bug?

谢谢.

推荐答案

根据

According to GCC's concurrency page, it's necessary to provide additional options to the compiler based on the features being used. You can verify that your version of GCC's threads rely on POSIX threads:

$ gcc -v 2>&1 | grep "Thread model"
Thread model: posix

请参见此错误报告,以了解行为的正当性:

See this bug report for a justification for the behavior:

问题在于,并非所有目标都需要-pthread,或者某些确实需要-pthread的拼写有所不同,并且在使用该选项时,并非所有平台都定义_REENTRANT,因此没有可靠的方法来执行您要的操作.

The problem is that not all targets need -pthread, or some which do need it spell it differently, and not all platforms define _REENTRANT when the option is used, so there's no reliable way to do what you're asking for.

这篇关于g ++-为什么我必须通过"-pthread"使用std :: thread时的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆