gpt4 book ai didi

c++ - 几个线程 : catching the moment when they all finish work

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

我有几个线程,我需要捕获它们全部完成工作的时刻。怎么做?

for (int i = 1; i < 3; i++) {
std::thread threads1(countFile, i);
i++;
std::thread threads2(countFile, i);
threads1.detach();
threads2.detach();
}

// wait until all the threads run out---

// to do next function ob object which uses by threads--

最佳答案

考虑在 for block 之外创建 std::thread 对象并调用 join() 而不是 detach() :

// empty (no threads associated to them yet)
std::array<std::thread, 2> threads1, threads2;

for (int i = 0; i < 2; i++) {
threads1[i] = std::thread(countFile, i+1); // create thread
i++;
threads2[i] = std::thread(countFile, i+1); // create thread
}

// ...

// join on all of them
for (int i = 0; i < 2; i++) {
threads1[i].join();
threads2[i].join();
}

// at this point all those threads have finished

不调用 detach() 意味着必须在 std 的析构函数之前调用 join()::thread 对象被调用(无论线程是否已经完成)。

出于这个原因,我将 std::thread 对象放在了 for block 之外。否则,必须在 for block 内调用 join()

关于c++ - 几个线程 : catching the moment when they all finish work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48595601/

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