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)
使用原子变量作为计数器,启动新线程时增加变量,线程完成后在线程中减少计数器。
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)