下面是一个示例代码,演示了如何在std::vectorstd::thread中两次加入std::thread,以确保线程的析构函数不会终止:
#include
#include
#include
void threadFunction(int id) {
std::cout << "Thread " << id << " started." << std::endl;
// 模拟一些工作
std::this_thread::sleep_for(std::chrono::seconds(id));
std::cout << "Thread " << id << " finished." << std::endl;
}
int main() {
std::vector threads;
// 第一次加入线程
threads.emplace_back(threadFunction, 1);
threads.emplace_back(threadFunction, 2);
threads.emplace_back(threadFunction, 3);
// 等待所有线程完成
for (auto& thread : threads) {
thread.join();
}
// 第二次加入线程
threads.emplace_back(threadFunction, 4);
threads.emplace_back(threadFunction, 5);
threads.emplace_back(threadFunction, 6);
// 等待所有线程完成
for (auto& thread : threads) {
thread.join();
}
return 0;
}
在上面的例子中,我们首先将3个线程添加到std::vectorstd::thread中,并等待它们完成。然后,我们再次将3个线程添加到std::vectorstd::thread中,并再次等待它们完成。这样做可以确保线程的析构函数不会在std::vectorstd::thread还存在有效线程时被调用。