c++ - 多线程递归任务同步

标签 c++ multithreading recursion

void Node::recursiveThing()
{
  for(auto iter = m_children.begin();
  iter != m_children.end();
  iter++)
  {
    s_threadPool->addTask(std::bind(&Node::recursiveThing, (*iter));
  }
}

int main()
{
  Node * hugeThree = makeHugeTreeMethod();
  std::future allIterationsDone = s_threadPool->addTask(std::bind(&Node::recursiveThing, hugeTree));
  allIterationsDone.wait(); // I want to somehow block here until all spawned child tasks are done.
}

是的。

所以我的问题是我想从一个任务中生成子任务,而这又会生成更多的子任务。这行得通,但我怎么知道所有派生的子任务都已完成?也许我需要制作一个线程安全列表,其中都附加了它们?

我在某处读到这在 c++17 中是可能的,但我现在需要一些东西,有什么想法吗?

最佳答案

嗯……
是的,C++17 std::when_all 在这里可能非常有用。

我能想到的一个解决方案(仅限伪代码!):

struct TreeTasks
   vector<child*> busyNodes
   mutex vectorLock
   condition_variable vectorCV
   thread taskChecker 

BeforeAll
 lock busyNodes
 add root-node's *this* to busyNodes
 unlock busyNodes
 launch taskChecker with taskChecker Routine

OnNodeTaskFinish
 lock vectorLock
 add child nodes pointers to busyNodes if exist
 remove *this* from busyNodes
 unlock busyNodes
 notify vectorCV

taskChecker Routine
  lock vectorLock
  wait on vectorCV(vectorLock) on predicate -> busyNodes.isEmpty()
  return done

这与线程池算法如何拆分任务非常相似。
我们有一个 vector ,其中包含正在处理的节点,
一个线程,大部分时间只是休眠并在 vector 上发生大小变化时唤醒。

当一个任务完成在一个节点上工作时,它可能会也可能不会将 child 追加到 vector 中,但无论如何都会将自己从 vector 中移除。 检查线程唤醒 - 如果 vector 为空 - 所有任务都已完成。

关于c++ - 多线程递归任务同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32779155/

相关文章:

java - 将日历存储在常量字段中以便稍后使用,避免在方法内创建它

java - 使用数据报 UDP 发送和接收确认

c++ - 使用for循环递归地乘以数组中的元素

c++ - 在 C++ 类实现中调用 C 函数

c++ - 如何有效地将 VkDispatchIndirectCommand 字段提高到 subgroupSize 的倍数

c++ - Ping 功能在 1020 次尝试后失败

c - 如何在 ANSI C 中终止一个 pthread

algorithm - F# 错误和归并排序

java - 在Java中查找集合组合的递归算法

c++ - 在扩展模板的类中初始化静态常量