views:

177

answers:

2

I have a worker class like the one below:

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

It's intended to be executed with boost::thread and boost::bind, like:

Worker worker;
boost::function<int()> th_func = boost::bind(&Worker::Do, &worker);
boost::thread th(th_func);
th.join();

My question is, how do I get the return value of Worker::Do?

Thanks in advance.

+1  A: 

I don't think you can get the return value.

Instead, you can store the value as a member of Worker:

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

And use it like so:

Worker worker;
boost::function<void()> th_func = boost::bind(&Worker::Do, &worker);
boost::thread th(th_func);
th.join();
//do something with worker.m_ReturnValue
Alex Deem
Thanks I guess I have to redesign a bit.
He Shiming
A: 

In addition, you also have some redundant calls to boost::bind() and boost::function(). You can instead do the following:

class Worker{
    public:
       void operator(){
          int ret = 100;
          // do stuff
          m_ReturnValue = ret;
       }
    int m_ReturnValue;
}

Worker worker;
boost::thread th(worker());//or boost::thread th(boost::ref(worker));

You can do this because Thread's constructor is a convenience wrapper around an internal bind() call. Thread Constructor with arguments

imran.fanaswala
That looks quite straightforward. Thanks but my actual implementation contains many member functions, so I can't really use the () operator.
He Shiming
imran.fanaswala