【问题标题】:How to use return values from functor's with boost::thread如何通过 boost::thread 使用仿函数的返回值
【发布时间】:2012-03-14 09:06:32
【问题描述】:

如果我有这样的仿函数...

class DoStuff {

  private:

    std::vector < int > numericStuff;

  public:

    explicit DoStuff (const std::vector <int> &newStuff) : numericStuff (newStuff) {};

    int operator () (void) {

       int ProcessedStuff = 0;

       //...Doing stuff

       return ProcessedStuff;

    };

};

...现在,如果我想正常使用它,我所要做的就是...

//...Vector declared and populated somewhere else
DoStuff stuff (Vector);
int someNumber = stuff();

...然后就可以了。我想做的就是像这样把它扔进一个 boost::thread ......

DoStuff stuff (Vector);
boost::thread (stuff);

...然后使用它,但对于我的生活,我不知道如何使用它。任何帮助将不胜感激。

【问题讨论】:

    标签: boost functor


    【解决方案1】:

    你不能这样做。要从线程“返回值”,您必须使用Futures。 引用上述文档:

    调用打包的任务时,会调用包含的函数 反过来,并用返回值填充未来。 这是一个 回答常年的问题:“我如何从 线程?”:把你想运行的函数打包成一个 boost::packaged_task 并将打包的任务传递给线程 构造函数。然后可以从打包任务中检索到的未来 用于获取返回值。如果函数抛出异常, 存储在将来代替返回值。

    【讨论】:

    • 我明白了,谢谢。我是新来的,当我阅读线程文档时我没有意识到这一点。我想我最好了解一下期货。
    猜你喜欢
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    相关资源
    最近更新 更多