C++11 future::wait_for compile error

C++11 future::wait_for compile error

本文关键字:compile error for wait future C++11      更新时间:2023-10-16

我正在尝试制作多线程应用程序,其中每个线程都将在不同的时间内处理任务。所以我想使用future和future::wait_fo函数。但当我只使用CPP参考的代码时

#include <iostream>
#include <future>
#include <thread>
#include <chrono>
int main()
{
    std::future<int> future = std::async(std::launch::async, [](){ 
        std::this_thread::sleep_for(std::chrono::seconds(3));
        return 8;  
    }); 
    std::cout << "waiting...n";
    std::future_status status;
    do {
        status = future.wait_for(std::chrono::seconds(1));
        if (status == std::future_status::deferred) {
            std::cout << "deferredn";
        } else if (status == std::future_status::timeout) {
            std::cout << "timeoutn";
        } else if (status == std::future_status::ready) {
            std::cout << "ready!n";
        }
    } while (status != std::future_status::ready); 
    std::cout << "result is " << future.get() << 'n';
}

我得到编译错误:

 thread.cpp:31:58: error: cannot convert ‘bool’ to ‘std::future_status’ in assignment

我使用的是ubuntu 12.04和gcc 4.6.3版本(ubuntu/Linaro 4.6.3-1ubuntu5)有什么想法吗?谢谢

G++4.6.3不完全支持C++11,因此更新到完全支持C++11的更高版本(即gcc 4.7或更高版本)将解决此类问题。或者使用clang 3.4(3.2支持很多C++11,但3.4支持更多,并且在此基础上进行了更好的优化)。

根据此提交日志,返回类型在2012年2月从bool更改为std::future_status,GCC 4.7(2012年3月22日)是wait_for新版本附带的第一个版本。

  • https://github.com/mirrors/gcc/commit/f7273180cc277a28a6779a21bfa5d5e878254c5f