多线程代码不会使用 g++ 进行编译,但可以使用 clang++

Multithreaded code won't compile using g++, but is fine with clang++

本文关键字:编译 clang++ 可以使 g++ 代码 多线程      更新时间:2023-10-16

我的g++编译器有问题。在我的工作机器(运行OS X 10.10.4(上,我正在尝试使用Xcode的一些代码。代码编译成功,生成的可执行文件按预期工作。clang++ --version:输出

Apple LLVM版本6.1.0(clang-602.0.53((基于LLVM 3.6.0svn(目标:x86_64-apple-darwin14.4.0线程型号:posix

然后我决定在运行Debian8的服务器上用g++编译这段代码。g++ --version:的输出

g++(Debian 4.9.2-22(4.9.2版权所有(C(2014自由软件基金会,股份有限公司

代码甚至不会使用g++进行编译。我尝试使用的命令:g++ -std=c++11 -pthread main.cpp

我收到以下错误消息:

main.cpp:在函数"int main(("中:

main.cpp:32:106:错误:无效使用不完整的类型"class std::packaged_task"std::shared_ptr>ptr(新std::packaged_task(std::bind(factorial,6(((;

在主.cpp中包含的文件中:11:0:

/usr/include/c++/4.9future:120:11:error:"class std::packaged_task"的声明类packaged_task;^

main.cpp:33:22:错误:变量"std::future fu1"具有初始值设定项,但类型不完整std::future fu1=ptr->get_future((;^

main.cpp:33:31:错误:无效使用不完整的类型"class std::packaged_task"std::future fu1=ptr->get_future((;^

在主.cpp中包含的文件中:11:0:

/usr/include/c++/4.9future:120:11:error:"class std::packaged_task"的声明类packaged_task;^

main.cpp:在lambda函数中:

main.cpp:34:48:错误:无效使用不完整的类型"class std::packaged_task"std::function task1=&ptr{ptr->运算符((;};^

在主.cpp中包含的文件中:11:0:

/usr/include/c++/4.9future:120:11:error:"class std::packaged_task"的声明类packaged_task;^

main.cpp:在函数"int main(("中:

main.cpp:36:38:错误:变量"std::packaged_task t"具有初始值设定项,但类型不完整std::packaged_task t(std::bind(阶乘,5((;^

main.cpp:37:22:error:变量"std::future fu2"具有初始值设定项,但类型不完整std::future fu2=t.get_future((;^

我的代码:

#include <iostream>
#include <thread>
#include <future>
#include <memory>
using std::cout;
using std::cin;
using std::endl;
unsigned long long int factorial(unsigned long long int num)
{
    unsigned long long int N = num;
    for (unsigned long long int i = num; i > 1; --i)
    {
        num *=(--N);
    }
    return num;
}
int main()
{
    std::shared_ptr<std::packaged_task<int()> > ptr(new std::packaged_task<int()>(std::bind(factorial, 6)));
    std::future<int> fu1 = ptr->get_future();
    std::function<void()> task1 = [&ptr](){ ptr->operator()(); };
    std::packaged_task<int()> t(std::bind(factorial, 5));
    std::future<int> fu2 = t.get_future();
    std::function<void()> task2 = [&t](){ t(); };
    std::thread threads[2];
    threads[0] = std::thread(task1);
    threads[1] = std::thread(task2);
    cout << fu1.get() << endl;
    cout << fu2.get() << endl;
    threads[0].join();
    threads[1].join();
    return 0;
}

g++可能有什么问题?

似乎,std::future&由于某些原因,std::async没有在armel架构上实现。

我真的不知道为什么会这样(有些人在邮件列表上争论,他们不是通过设计实现的,有些人说这是一个bug(,以及问题的当前状态。

然而,我也发现了一个回复,其中指出可能已经在较新版本的libstdc++中得到了解决(我的系统正在运行debian的测试版本,我还没有这些版本,我不打算从不稳定的repos中获得包,所以我只等它(。