我们可以使用容器保存一组线程,如下面的vector装入一组线程:
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
void func(int n)
{
std::string str = std::to_string(n);
str += '\n';
std::cout << str.c_str();
}
int main()
{
std::cout << "Hello World!\n";
std::vector<std::thread> thrds;
for (int i = 0; i < 120; i++)
{
std::thread t(func, i);
thrds.push_back(std::move(t));
}
for (size_t i = 0; i < thrds.size(); i++)
{
thrds[i].detach();
}
std::this_thread::sleep_for(std::chrono::seconds(6));
std::cout << "that is ok" << std::endl;
return 0;
}