【问题标题】:passing std::future to a boost::thread vs a std::thread将 std::future 传递给 boost::thread 与 std::thread
【发布时间】:2020-12-15 05:59:49
【问题描述】:

我似乎无法弄清楚为什么以下代码使用 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;
}

【问题讨论】:

    标签: c++ multithreading promise future boost-thread


    【解决方案1】:

    因为boost::thread(function, args)构造函数被指定为

    好像thread(boost::bind(f,a1,a2,...))

    boost::bind 在调用底层函数时复制参数而不是移动它们(因为它必须允许多次调用)。

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

    std::thread 没有这样的限制,并指定参数被移动。

    【讨论】:

    • 那么我应该怎么做才能让它工作呢? std::move 还不够吗?我试过 boost::ref/std::ref 一切..
    • @ashishsony 您可以尝试发送shared_future 来代替吗?那还是一回事吗?我对 C++ 的了解并不完全最新。与启动新线程相比,性能损失应该可以忽略不计。
    • 谢谢,std::shared_future 与 boost::thread 一起工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多