fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. void f(int n) {
  7. for (int i = 0; i < 10; ++i) {
  8. std::cout << "Message from thread #" << n << ": iteration #" << i << "\n";
  9. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10. }
  11. }
  12.  
  13. int main() {
  14. std::cout << "Main thread: build threads pool\n";
  15. std::vector<std::thread> pool;
  16. pool.push_back(std::thread{f, 1});
  17. pool.push_back(std::thread{f, 2});
  18. pool.push_back(std::thread{f, 3});
  19. std::for_each(pool.begin(), pool.end(), std::mem_fn(&std::thread::join));
  20. std::cout << "Main thread: all threads finished.\n";
  21. }
Success #stdin #stdout 0s 9616KB
stdin
Standard input is empty
stdout
Main thread: build threads pool
Message from thread #3: iteration #0
Message from thread #2: iteration #0
Message from thread #1: iteration #0
Message from thread #3: iteration #1
Message from thread #2: iteration #1
Message from thread #1: iteration #1
Message from thread #2: iteration #2
Message from thread #3: iteration #2
Message from thread #1: iteration #2
Message from thread #3: iteration #3
Message from thread #2: iteration #3
Message from thread #1: iteration #3
Message from thread #2: iteration #4
Message from thread #3: iteration #4
Message from thread #1: iteration #4
Message from thread #2: iteration #5
Message from thread #3: iteration #5
Message from thread #1: iteration #5
Message from thread #3: iteration #6
Message from thread #2: iteration #6
Message from thread #1: iteration #6
Message from thread #3: iteration #7
Message from thread #2: iteration #7
Message from thread #1: iteration #7
Message from thread #3: iteration #8
Message from thread #2: iteration #8
Message from thread #1: iteration #8
Message from thread #3: iteration #9
Message from thread #2: iteration #9
Message from thread #1: iteration #9
Main thread: all threads finished.