Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for all threads in C++

I'm using the construct "thread" in C++ and I create a variable number of thread in a recursive function. I want the main thread to wait for all of them. How can I do it without WaitForMultipleObjects ?

like image 914
Seba92 Avatar asked May 18 '15 07:05

Seba92


3 Answers

Take a look at example in cplusplus. Store threads with emplace_back() in vector. At the end you have loop with joins.

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();
like image 57
M.L. Avatar answered Oct 16 '22 20:10

M.L.


Use an atomic variable as a counter, increase the variable when launching new thread, in the thread decrease the counter once the thread is completed.

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; });
}
like image 4
Min Lin Avatar answered Oct 16 '22 20:10

Min Lin


You could also use boost thread_group. It only works with boost threads, but they have a nearly identical interface to std::thread (boost threads were the basis for threads in the standard library in C++11), and once you add all your threads to the thread_group, you simply call join_all on the group. You could also implement a thread_group class of your own, to work with std::thread, which would essentially do what has already been suggested, with a vector of thread objects or pointers, and waits on them in a loop.

like image 2
Elkvis Avatar answered Oct 16 '22 20:10

Elkvis