passing std::future to a boost::thread vs a std::thread

373 views Asked by At

I cant seem to figure out why the following code compiles with std::thread, but not with boost::thread,gives the following error on msvs 2015.

Severity Code Description Project File Line Suppression State Error C2280 'std::future::future(const std::future &)': attempting to reference a deleted function

#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;
}
1

There are 1 answers

3
Sebastian Redl On

Because boost::thread's (function, args) constructor is specified as

As if thread(boost::bind(f,a1,a2,...))

and boost::bind copies arguments instead of moving them when calling the underlying function (because it has to allow multiple calls).

Why is it this way? Possibly due to backwards-compatibility with pre-move Boost.Thread versions.

std::thread has no such restriction and specifies that the arguments are moved.