1

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?

Tim
  • 834
  • 2
  • 12
  • 31
  • 1
    Are you looking for something like [std::async](http://en.cppreference.com/w/cpp/thread/async) without using C++11? – nosid Sep 30 '13 at 07:06
  • [This answer might help](http://stackoverflow.com/a/1713427/220636) – nabulke Sep 30 '13 at 07:09
  • Thanks. That answers half my question. The other bit is how can i pass *in* the data – Tim Sep 30 '13 at 07:12
  • The `boost::thread` constructor _copies_ the data you provide. You can avoid the copy by using `boost::ref`. – nabulke Sep 30 '13 at 07:18
  • @nabulke but that opens up a window for data races obviously. Consider _moving_ the parameter to the thread. Threads and shared (mutable) state aren't generally recommendable (certainly not just to "avoid the copy") – sehe Sep 30 '13 at 07:21

1 Answers1

1

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();
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Here's an adaptation that passes the message: http://coliru.stacked-crooked.com/a/aa6f070e2a6e8d0e – sehe Sep 30 '13 at 07:17
  • And one for if the messages are not copyable but move-only: http://coliru.stacked-crooked.com/a/82c99be9b35830ad – sehe Sep 30 '13 at 07:19
  • This makes sense, but VS2010 doesn't support std::async. How can I get it to work with boost? – Tim Sep 30 '13 at 07:32
  • It seems it got added http://www.boost.org/doc/libs/1_54_0/doc/html/thread/synchronization.html#thread.synchronization.futures.async but there's a [warning](http://www.boost.org/doc/libs/1_54_0/doc/html/thread/synchronization.html#thread.synchronization.futures.reference.async) too – sehe Sep 30 '13 at 07:40