fork(1) download
  1. #include <iostream>
  2. #include <thread>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <mutex>
  6. #include <chrono>
  7.  
  8. using namespace std;
  9.  
  10.  
  11. struct Data
  12. {
  13. mutex lock;
  14. vector<char> v;
  15. char current = 'A';
  16.  
  17. } data;
  18.  
  19. char next(char ch)
  20. {
  21. switch(ch)
  22. {
  23. case 'A': return 'B';
  24. case 'B': return 'C';
  25. case 'C': return 'A';
  26. }
  27. }
  28.  
  29. void threadSafeOrderedPrint(char ch)
  30. {
  31. lock_guard<mutex> l(data.lock);
  32. data.v.push_back(ch);
  33. while(!data.v.empty())
  34. {
  35. auto it = find(begin(data.v),end(data.v),data.current);
  36. if(it==end(data.v))
  37. return;
  38.  
  39. cout<< *it;
  40. data.current = next(data.current);
  41. data.v.erase(it);
  42. }
  43. }
  44.  
  45.  
  46. void foo(const char ch)
  47. {
  48. for (int i=0; i<25; ++i)
  49. {
  50. this_thread::sleep_for(chrono::milliseconds(10));
  51. threadSafeOrderedPrint(ch);
  52. }
  53. }
  54.  
  55. int main()
  56. {
  57. vector<thread> threads;
  58. threads.reserve(3);
  59. threads.emplace_back(foo, 'A');
  60. threads.emplace_back(foo, 'B');
  61. threads.emplace_back(foo, 'C');
  62.  
  63. for(auto & t : threads)
  64. t.join();
  65.  
  66. cout<<endl<<"Finished"<<endl;
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0s 4528KB
stdin
Standard input is empty
stdout
ABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABC
Finished