众所周知,我们可以通过std :: thread t1(func);生成一个线程。 link 但是,如何通过向量创建20个线程?
jiay87 回答:如何通过std :: thread生成许多线程?
解决方案的示例是:
std::vector<std::thread> my_threads{};
my_threads.reserve(20);
for(int i = 0; i < 20; i++)
my_threads.emplace_back([i]{
std::cout << "[" << i << "] Going to sleep\n";
this_thread::sleep_for(std::chrono::seconds{1});
std::cout << "[" << i << "] Hey I'm back :)\n";
});
for(auto& thread : my_threads)
if(thread.joinable())
thread.join();
请注意最后的树线。
如果不加入或分离线程,则会中止操作。
这样可以防止您的应用程序泄漏非托管线程。