Getting return value from a boost::threaded member function?

前端 未结 5 1424
星月不相逢
星月不相逢 2020-12-17 01:19

I have a worker class like the one below:

class Worker{
public:
  int Do(){
    int ret = 100;
    // do stuff
    return ret;
  }
}

It\'s

5条回答
  •  时光取名叫无心
    2020-12-17 01:50

    Another option is to use promises/futures.

    class Worker{
    public:
      void Do( boost::promise & p){
        int ret = 100;
        // do stuff
        p.set_value(ret);
      }
    };
    //Later...
    boost::promise p;
    boost::thread t( boost::bind(&Worker::Do, &worker, boost::ref(p));
    int retval = p.get_future().get(); //This will block until the promise is set.
    

    And if you can use c++0x, then using std::async will package up all of the above and just do:

    std::future f = std::async( std::bind(&Worker::Do, &worker) );
    int retval = f.get(); //Will block until do returns an int.
    

提交回复
热议问题