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