在c++中等待所有线程

Wait for all threads in C++

本文关键字:线程 等待 c++      更新时间:2023-10-16

我使用c++中的"thread"结构,并在递归函数中创建了可变数量的线程。我想让主线程等待所有这些。我怎么能做到没有WaitForMultipleObjects ?

看一下cplusplus中的例子。使用emplace_back()将线程存储在vector中。在循环的最后,你有连接。

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();

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

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; });
}

您也可以使用boost thread_group。它只适用于boost线程,但它们具有与std::thread几乎相同的接口(boost线程是c++ 11中标准库中线程的基础),并且一旦将所有线程添加到thread_group中,只需在该组上调用join_all。您还可以实现自己的thread_group类,以使用std::thread,它本质上是使用线程对象或指针的向量,并在循环中等待它们。

我不知道你的具体情况,但这种方法可能对你有用。

using thread_vec = std::vector<std::thread>;
void batch_process(int n)
{
    static std::mutex mtx;
    std::lock_guard<std::mutex> lock(mtx);
    std::cout << "process: " << n << 'n';
}
void recursive(thread_vec& tv, int n)
{
    // do some stuff
    tv.emplace_back(batch_process, n);
    if(n > 0)
        recursive(tv, n - 1);
}
int main(int, char* argv[])
{
    thread_vec tv;
    recursive(tv, 3);
    for(auto&& t: tv)
        t.join();
}
输出:

process: 1
process: 0
process: 2
process: 3