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 上发生大小更改时,大多数情况下只是休眠并唤醒的线程。
当任务完成在节点上的工作时,它可能会(也可能不会)将子代添加到 vector 中,但是无论如何都会从 vector 中删除自身。
检查线程唤醒-如果 vector 为空-完成所有任务。