[英]how to generate many threads by 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();
注意最后的树线。 如果您不加入或分离线程,您将中止。
这可以防止您的应用程序泄漏非托管线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.