带有asycron的c++boost thread_group返回

c++ boost thread_group with asycron returns

本文关键字:group 返回 thread c++boost asycron 带有      更新时间:2023-10-16

我正在尝试编写一个函数,该函数同时处理线程组中线程的输入参数和返回值。

我的示例类:

  // 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;

示例代码:

  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);
   }
 }

我想遍历线程,并能够检查DoWork是否返回true。

我该如何实现?

首先,使用thread_group,您不能迭代线程对象。因此,如果这是您想要的,请考虑将线程对象存储在其他容器中。

此外,您不能便携地等到一个线程完成,但如果您不介意使用特定于Windows的API,则可以使用WaitForMultipleObjects来完成此操作。

但是,我建议您重新设计您的应用程序,以避免此类技巧。