Всякий раз, когда вы используете темы, есть три части.
- Запуск потоков
- Выполнение работы
- Освобождение потока
Вы запускаете темы и выполняете работу,но ты их не отпускаешь.
Освобождение потоков. Существует два варианта освобождения потока.
- Вы можете присоединиться к потоку (который в основном ожидает его завершения)
- Вы можете отсоединить поток и позволить ему выполняться независимо.
В этом конкретном случае вы не хотите, чтобы программа заканчивала работу до тех пор, пока не завершатся все потоки, поэтому вам следует присоединиться к ним.
#include <iostream>
#include <thread>
#include <vector>
#include <string>
auto call_from_thread = [](int i) {
// I create the entire message before printing it, so that there's no interleaving of messages between threads
std::string message = "Calling from thread " + std::to_string(i) + '\n';
// Because I only call print once, everything gets printed together
std::cout << message;
};
using std::thread;
int main() {
thread t[500];
for(int i=0; i<500; i++) {
// Here, I don't have to start the thread with any delay
t[i] = thread(call_from_thread, i);
}
std::cout << "main fun start\n";
// I join each thread (which waits for them to finish before closing the program)
for(auto& item : t) {
item.join();
}
return 0;
}