在c++中等待所有线程
Wait for all threads in C++
我使用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
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 提升 ASIO - io_service 不要等待连接到线程
- 虚假唤醒是否会解锁所有等待线程,甚至是不相关的线程?
- 一个线程等待多个线程事件
- 如何让线程等待对象完全破坏?(对象也有一个线程)?
- 停止C++ 11 个 std::线程等待 std::condition_variable
- C++线程:等待condition_variable后无法解锁阵列中的互斥锁
- Qt 线程等待来自 GUI 的输入
- C++11线程等待
- 如何让线程等待对象的销毁
- Boost:等待工作线程等待条件变量
- C++11线程等待行为:std::this_Thread::yield()与std::this _Thread::sle
- 如何使线程等待而不轮询
- 使其中一个线程等待的时间尽可能少(几乎为零)
- 当线程等待互斥锁时捕获的信号
- Qt:如何让一个线程等待临时包障,并暂时增加另一个线程的优先级以删除 roadbock?
- C++ Windows MFC 并发:让线程等待,直到达到特定状态
- 线程等待父线程
- 使用异步方法vs线程等待
- c++线程等待时间