c++ boost thread_group with asycron returns

I´m trying to write a function that handles both input arguments and return values from a thread in a thread group.

My example class:

  // includes...
class MyClass(int id)
  {
  thread_id = id;
  i = id* 5; 
  b = false;
 }

void resetCounter(int j){
  i = j * 5;
 }
int getId(){
 return id;
}
bool getBool(){
  return b;
 }

void DoWork(){
  while( i > 0 ){
     boost::this_thread::sleep(boost::posix_time::seconds(i));
      i--;
  }
  b = true;  // DoWork will in the real code be able to return false!
  }
  private:
  bool b;
  int i;
  int thread_id
 };

  boost::threadgroup threads;

Exemple code:

  bool exist = false;
  for(int i=0;i<4;i++){
  // first check if thread id exist (possible)? 
  // If so don´t create a new thread but reset the counter!
  if(exist){
   // in current thread call reset "i" (w.resetCounter(i))
   }else{
    MyClass m(i);
    boost::function<void()> thread_func = boost::bind(&MyClass::DoWork, &m);
    threads.create_thread(thread_func);
   }
 }

I want to iterate through the threads and be able to check if DoWork returned true.

How do I implement this?

Answers


First of all, with thread_group you can't iterate over the thread objects. So if this's what you want, consider storing thread objects in some other container.

Besides, you can't portably wait until one thread finishes, but if you don't mind using Windows-specific API, you can do this with WaitForMultipleObjects.

However, I would recommend you re-designing your application, to avoid such tricks.


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.