等待C++中的所有线程

Seb*_*a92 10 c++ multithreading c++11

我在C++中使用构造"线程",我在递归函数中创建了一个可变数量的线程.我希望主线程等待所有这些.没有WaitForMultipleObjects我怎么能这样做?

M.L*_*.L. 25

看看cplusplus 中的例子.它们在向量中存储带有push_back()的线程.最后你有连接循环.

std::vector<std::thread> threads;
//create threads
for (int i=1; i<=10; ++i)
    threads.emplace_back(std::thread(increase_global,1000));
//wait for them to complete
for (auto& th : threads) 
    th.join();
Run Code Online (Sandbox Code Playgroud)

  • cplusplus.com已经形成了相当大的优势.低估一个引用它的答案_不具有建设性.调出cplusplus.com _is_ constructive实际上错误的细节. (14认同)
  • `emplace_back`在这里可能更好. (5认同)
  • 为什么这是downvote的原因? (2认同)
  • 不是我的投票,但它通常不如cppreference.com准确. (2认同)
  • @Puppy:感谢您提供具体示例。当我同意其中的一些时,我看不出for循环有什么奇怪的。您声称“他们甚至不能编写简单的数字`for`循环”,但我找不到您似乎已发现的明显错误。 (2认同)

Min*_*Lin 5

使用原子变量作为计数器,启动新线程时增加变量,线程完成后在线程中减少计数器。

int main() {
    mutex m;
    condition_variable cv;
    atomic<int> counter = 0;

    // .... in your recursive call
    // increase counter when launching thread.
    counter++;
    thread t([](){
        // do whatever
        lock_guard<mutex> lk(m);
        counter--;
        cv.notify_all();
    });
    t.detach(); // no need to join anymore.
    // .... end recursive call

    unique_lock<mutex> lock(m);
    cv.wait(lock, [](){ return counter == 0; });
}
Run Code Online (Sandbox Code Playgroud)

  • @mg30rg 条件变量是阻塞而不是轮询,线程连接也是阻塞的。 (6认同)