fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <atomic>
  5.  
  6. static const int num_threads = 10;
  7.  
  8. std::atomic<int> cnt{0};
  9.  
  10. //This function will be called from a thread
  11.  
  12. void call_from_thread(int tid) {
  13. while (cnt!=tid)
  14. std::this_thread::yield();
  15. std::cout << "Launched by thread " << tid << std::endl;
  16. cnt++;
  17. }
  18.  
  19. int main() {
  20. std::thread t[num_threads];
  21.  
  22. //Launch a group of threads
  23. for (int i = 0; i < num_threads; ++i) {
  24. t[i] = std::thread(call_from_thread, i);
  25. }
  26.  
  27. std::cout << "Launched from the main\n";
  28.  
  29. //Join the threads with the main thread
  30. for (int i = 0; i < num_threads; ++i) {
  31. t[i].join();
  32. }
  33.  
  34. return 0;
  35. }
Success #stdin #stdout 0.05s 23952KB
stdin
Standard input is empty
stdout
Launched from the main
Launched by thread 0
Launched by thread 1
Launched by thread 2
Launched by thread 3
Launched by thread 4
Launched by thread 5
Launched by thread 6
Launched by thread 7
Launched by thread 8
Launched by thread 9