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 ?
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();
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; });
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With