【问题标题】:use boost::bind and boost::thread with return values使用带返回值的 boost::bind 和 boost::thread
【发布时间】:2013-10-05 23:00:34
【问题描述】:

我想创建一个在另一个线程中运行的函数版本:

errType sendMessage(Message msg,Message* reply);

像这样:

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

我想要做的是将参数传递给函数并存储返回值。 我该怎么做?

【问题讨论】:

  • 您是否正在寻找类似std::async 的东西而不使用 C++11?
  • 谢谢。这回答了我一半的问题。另一点是我如何传递 in 数据
  • boost::thread 构造函数复制您提供的数据。您可以使用boost::ref 避免复制。
  • @nabulke 但这显然为数据竞争打开了一个窗口。考虑将参数移动到线程。通常不推荐使用线程和共享(可变)状态(当然不仅仅是为了“避免复制”)

标签: c++ boost-thread boost-bind


【解决方案1】:

如果你要这样使用它,不会有太大的收获。但是,典型的用法是

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

然后,例如。

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

// do other work here

errType result = fut.get();

这是一个完整的演示(为缺少的元素填充存根):**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();
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 2011-09-28
相关资源
最近更新 更多