【问题标题】:c++ boost thread_group with asycron returnsc++ boost thread_group with asycron 返回
【发布时间】:2012-09-08 21:42:36
【问题描述】:

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

我的示例类:

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

我该如何实现?

【问题讨论】:

  • 到底是什么问题?
  • 我想实现这个伪代码但不知道怎么做。实际上有多个问题。
  • 最重要的是我将如何在完成后创建一个线程等待 1 秒以等待其他线程完成。然后收集在那一秒内完成的一组“thread-ID:s”:但前提是“DoWork”返回 true。
  • 我也希望能够,给定一个特殊的“thread-ID”(顺便说一句,它可能是一个字符串,并且请求的“thread-ID”将通过参数列表传递给这个函数) , 检查线程 ID 是否正在运行。如果线程仍在运行,那么我想重置它的计数器。否则......如果它被请求但没有运行,那么它应该被创建。
  • 这毫无意义:线程可能在你检查它的那一刻正在运行,但下一刻就结束了。

标签: c++ multithreading boost boost-thread


【解决方案1】:

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

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

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

【讨论】:

  • 我发现了另一种方法来通过重新设计我的应用程序来实现我所需要的,因此接受它作为最终答案。
猜你喜欢
  • 1970-01-01
  • 2012-04-11
  • 1970-01-01
  • 2013-05-16
  • 2013-10-01
  • 2015-01-28
  • 1970-01-01
  • 2015-09-04
  • 1970-01-01
相关资源
最近更新 更多