gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:16:38 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com