简体   繁体   中英

use boost::bind and boost::thread with return values

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM