fork download
  1. #include <atomic>
  2. #include <chrono>
  3. #include <iostream>
  4. #include <mutex>
  5. #include <queue>
  6. #include <thread>
  7.  
  8. std::mutex gMutex;
  9. std::queue<int> gQueue;
  10. std::atomic<bool> gRunThread(true);
  11. std::thread gWorkerThread;
  12.  
  13. void workerThread();
  14.  
  15. void driver();
  16.  
  17. void start();
  18.  
  19. void addData(int i);
  20.  
  21. void end();
  22.  
  23. int main()
  24. {
  25. std::thread driverThread(&driver);
  26. driverThread.join();
  27.  
  28. return 0;
  29. }
  30.  
  31. void driver()
  32. {
  33. std::cout << "Starting ...\n";
  34. std::this_thread::sleep_for(std::chrono::seconds(1));
  35. start();
  36.  
  37. std::this_thread::sleep_for(std::chrono::seconds(1));
  38. for (auto i = 0; i < 5; ++i)
  39. {
  40. std::this_thread::sleep_for(std::chrono::seconds(1));
  41. addData(i);
  42. }
  43.  
  44. std::cout << "Ending ...\n";
  45. std::this_thread::sleep_for(std::chrono::seconds(1));
  46. end();
  47. }
  48.  
  49. void workerThread()
  50. {
  51. while (gRunThread)
  52. {
  53. bool isEmpty;
  54.  
  55. {
  56. std::lock_guard<std::mutex> lock(gMutex);
  57. isEmpty = gQueue.empty();
  58. }
  59.  
  60. if (isEmpty)
  61. {
  62. std::cout << "Waiting for the queue to fill ...\n";
  63. std::this_thread::sleep_for(std::chrono::seconds(2));
  64. }
  65. else
  66. {
  67. std::lock_guard<std::mutex> lock(gMutex);
  68.  
  69. int value = gQueue.front();
  70. gQueue.pop();
  71.  
  72. std::cout << "Dequeued: " << value << "\n";
  73. }
  74. }
  75. }
  76.  
  77. void start()
  78. {
  79. gWorkerThread = std::thread(&workerThread);
  80. }
  81.  
  82. void addData(int i)
  83. {
  84. {
  85. std::lock_guard<std::mutex> lock(gMutex);
  86. gQueue.push(i);
  87. }
  88.  
  89. std::cout << "Queued: " << i << "\n";
  90. }
  91.  
  92. void end()
  93. {
  94. gRunThread = false;
  95. gWorkerThread.join();
  96. }
  97.  
Success #stdin #stdout 0s 20832KB
stdin
Standard input is empty
stdout
Starting ...
Waiting for the queue to fill ...
Waiting for the queue to fill ...
Queued: 0
Queued: 1
Dequeued: 0
Dequeued: 1
Waiting for the queue to fill ...
Queued: 2
Queued: 3
Dequeued: 2
Dequeued: 3
Waiting for the queue to fill ...
Queued: 4
Ending ...