fork 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 35768KB
stdin
Standard input is empty
stdout
main(): 47463952603072
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
9 : 21
7 : 22
8 : 23
5 : 24
1 : 25
2 : 26
3 : 27
4 : 28
6 : 29
0 : 30
8 : 31
5 : 32
7 : 33
1 : 34
2 : 35
9 : 36
4 : 37
3 : 38
6 : 39
0 : 40
7 : 41
5 : 42
1 : 43
2 : 44
4 : 45
9 : 46
3 : 47
8 : 48
6 : 49
0 : 50
1 : 51
5 : 52
4 : 53
2 : 54
9 : 55
7 : 56
3 : 57
8 : 58
6 : 59
0 : 60
2 : 61
4 : 62
5 : 63
9 : 64
7 : 65
8 : 66
6 : 67
1 : 68
3 : 69
0 : 70
2 : 71
5 : 72
9 : 73
4 : 74
7 : 75
8 : 76
1 : 77
6 : 78
3 : 79
0 : 80
5 : 81
4 : 82
9 : 83
7 : 84
8 : 85
1 : 86
6 : 87
3 : 88
2 : 89
0 : 90
9 : 91
4 : 92
7 : 93
8 : 94
5 : 95
1 : 96
3 : 97
6 : 98
2 : 99
0 : 100
~Tracker()47463952603072