fork(1) download
  1. #include <iostream>
  2. #include <atomic>
  3. #include <mutex>
  4. #include <thread>
  5. #include <vector>
  6.  
  7. std::mutex cout_mutex;//std::cout is not natively synchronized.
  8.  
  9. class Tracker{
  10. public:
  11. int get(){
  12. return ++counter;
  13. }
  14.  
  15. Tracker():counter(0){}
  16. ~Tracker(){
  17. std::lock_guard<std::mutex> guard{cout_mutex};
  18. std::cout<<"~Tracker()"<<std::this_thread::get_id()<<std::endl;
  19. }
  20.  
  21. private:
  22. std::atomic<int> counter;
  23. };
  24.  
  25.  
  26. std::atomic<bool> stop_flag;
  27. std::vector<std::thread> threads;
  28.  
  29. Tracker tracker;
  30.  
  31. void chug(size_t index){
  32. while(!stop_flag){
  33. {
  34. std::lock_guard<std::mutex> guard{cout_mutex};
  35. std::cout<<index<<" : "<<tracker.get()<<std::endl;
  36. }
  37. std::this_thread::sleep_for(std::chrono::milliseconds(10));//slow it down!
  38. }
  39. }
  40.  
  41.  
  42. //stop_all brings all the threads to a safe and known conclusion.
  43. void stop_all(){
  44. stop_flag=true;
  45. for( auto& curr: threads){
  46. curr.join();
  47. }
  48. }
  49.  
  50. void detach_all(){
  51. for( auto& curr: threads){
  52. curr.detach();
  53. }
  54. }
  55.  
  56.  
  57. int main() {
  58. const size_t num{10};
  59.  
  60. std::cout << "main(): "<<std::this_thread::get_id()<<'\n';
  61.  
  62. for(size_t i=0;i<num;++i){
  63. threads.emplace_back(chug,i);
  64. }
  65.  
  66. std::this_thread::sleep_for(std::chrono::milliseconds(100));//Let it run!
  67.  
  68. detach_all();
  69.  
  70. return 0;
  71. }
  72.  
  73.  
Success #stdin #stdout 0s 36592KB
stdin
Standard input is empty
stdout
main(): 47746502309824
6 : 1
7 : 2
8 : 3
9 : 4
5 : 5
4 : 6
3 : 7
2 : 8
1 : 9
0 : 10
6 : 11
7 : 12
8 : 13
9 : 14
5 : 15
4 : 16
3 : 17
2 : 18
1 : 19
0 : 20
7 : 21
9 : 22
5 : 23
1 : 24
4 : 25
2 : 26
3 : 27
8 : 28
6 : 29
0 : 30
9 : 31
5 : 32
1 : 33
4 : 34
3 : 35
2 : 36
8 : 37
6 : 38
7 : 39
0 : 40
5 : 41
4 : 42
1 : 43
3 : 44
2 : 45
8 : 46
9 : 47
6 : 48
7 : 49
0 : 50
4 : 51
1 : 52
3 : 53
2 : 54
5 : 55
8 : 56
9 : 57
6 : 58
7 : 59
0 : 60
1 : 61
3 : 62
2 : 63
5 : 64
8 : 65
9 : 66
4 : 67
6 : 68
7 : 69
0 : 70
3 : 71
1 : 72
2 : 73
5 : 74
8 : 75
9 : 76
4 : 77
6 : 78
7 : 79
0 : 80
1 : 81
2 : 82
5 : 83
3 : 84
8 : 85
9 : 86
4 : 87
6 : 88
7 : 89
0 : 90
2 : 91
5 : 92
3 : 93
8 : 94
9 : 95
4 : 96
1 : 97
6 : 98
7 : 99
0 : 100
~Tracker()47746502309824