将std :: future传递给boost :: thread与std :: thread

问题描述

我似乎无法弄清楚为什么以下代码使用std :: thread进行编译, 但没有boost :: thread,在msvs 2015上会出现以下错误

严重性代码描述项目文件行抑制状态 错误C2280'std :: future :: future(const std :: future&)': 试图引用已删除功能

#include <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include <future>
#include <boost/thread/thread.hpp>
void threadFunction(std::future<void> futureObj)
{
    std::cout << "Thread Start" << std::endl;
    while (futureObj.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout)
    {
        std::cout << "Doing Some Work" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    std::cout << "Thread End" << std::endl;
}
int main()
{
    // Create a std::promise object
    std::promise<void> exitSignal;
    //Fetch std::future object associated with promise
    std::future<void> futureObj = exitSignal.get_future();
    // Starting Thread & move the future object in lambda function by reference
    std::thread th(&threadFunction,std::move(futureObj));
    //boost::thread th(&threadFunction,std::move(futureObj));//this gives error
    //Wait for 10 sec
    std::this_thread::sleep_for(std::chrono::seconds(10));
    std::cout << "Asking Thread to Stop" << std::endl;
    //Set the value in promise
    exitSignal.set_value();
    //Wait for thread to join
    th.join();
    std::cout << "Exiting Main Function" << std::endl;
    return 0;
}

解决方法

由于boost::thread的{​​{1}}构造函数被指定为

好像(function,args)

thread(boost::bind(f,a1,a2,...))复制参数而不是在调用基础函数时将其移动(因为它必须允许多次调用)。

为什么这样?可能是由于与向前移动的Boost.Thread版本向后兼容。

boost::bind没有这种限制,并指定要移动参数。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...