36 lines · cpp
1#include <iostream>2#include <mutex>3#include <string>4#include <thread>5#include <vector>6 7void spawn_thread(int index) {8 std::string name = "I'm thread " + std::to_string(index) + " !";9 bool done = false;10 std::string state = "Started execution!";11 while (true) {12 if (done) // also break here13 break;14 }15 16 state = "Stopped execution!";17}18 19int main() {20 constexpr size_t num_threads = 10;21 std::vector<std::thread> threads;22 23 for (size_t i = 0; i < num_threads; i++) {24 threads.push_back(std::thread(spawn_thread, i));25 }26 27 std::cout << "Spawned " << threads.size() << " threads!" << std::endl; // Break here28 29 for (auto &t : threads) {30 if (t.joinable())31 t.join();32 }33 34 return 0;35}36