Question

i want to create a version of this function which runs in another thread:

errType sendMessage(Message msg,Message* reply);

like this:

errType async_sendMessage(Message msg,Message* reply){
    boost::thread thr = boost::thread(boost::bind(&sendMessage, this));
    return (return value of function);
}

What i want to do is pass in the parameters to the function and store the return value. How can I do this?

Was it helpful?

Solution

If you're going to use it like that, there won't be much gain. However, the typical usage would be

std::future<errType> async_sendMessage(Message msg,Message* reply){
    auto fut = std::async(&MyClass::sendMessage, this);
    return fut;
}

and then, eg.

Message msg;
auto fut = object.async_sendMessage(msg, nullptr);

// do other work here

errType result = fut.get();

Here's a full demo (filling in stubs for the missing elements): **Live on Coliru

#include <future>

struct Message {};
struct errType {};

struct MyClass
{
    std::future<errType> async_sendMessage(Message msg,Message* reply){
        auto fut = std::async(std::bind(&MyClass::sendMessage, this));
        return fut;
    }
  private:
    errType sendMessage() {
        return {};
    }
};

int main()
{
    MyClass object;
    Message msg;
    auto fut = object.async_sendMessage(msg, nullptr);

    errType result = fut.get();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top