Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class MyBackground {
  4. public:
  5. MyBackground()
  6. {
  7. m_workerThread = std::thread(&MyBackground::work, this);
  8. }
  9. ~MyBackground()
  10. {
  11. g_exit = true;
  12. workerThread.join();
  13. }
  14.  
  15. private:
  16. void work()
  17. {
  18. while(!m_exit);
  19. }
  20.  
  21. private:
  22. std::atomic<bool> m_exit{false};
  23. std::thread m_workerThread;
  24. };
  25.  
  26.  
  27. int main(int argc, char* argv[])
  28. {
  29. MyBackground object;
  30.  
  31. // here ther's some async background work
  32. return EXIT_SUCCESS;
  33.  
  34. // ~MyBackground -> here threads are stopped
  35. }
  36.  
  37. #include <csignal>
  38. #include <iostream>
  39. #include <thread>
  40.  
  41. using namespace std
  42.  
  43. atomic<bool> g_Exit{false};
  44.  
  45. void signalExit(int)
  46. {
  47. g_Exit = true;
  48. }
  49.  
  50. int main(int argc, char* argv[])
  51. {
  52. signal(SIGINT, signalExit);
  53. signal(SIGTERM, signalExit);
  54.  
  55. MyBackground object;
  56.  
  57. while (!g_Exit)
  58. this_thread::sleep_for(chrono::seconds{1});
  59.  
  60. // here ther's some async background work
  61. return EXIT_SUCCESS;
  62.  
  63. // ~MyBackground -> here threads are stopped
  64. }
  65.  
  66. #include <csignal>
  67. #include <iostream>
  68. #include <thread>
  69. #include <mutex>
  70. #include <condition_variable>
  71.  
  72. using namespace std
  73.  
  74. bool g_exitFlag = false;
  75. condition_variable g_exitCondition;
  76. mutex g_exitMutex;
  77.  
  78. using Lock = unique_lock<mutex>;
  79.  
  80. void signalExit(int)
  81. {
  82. Lock lock{g_exitMutex};
  83. g_exitFlag = true;
  84. g_exitCondition.notify_one();
  85. }
  86.  
  87. int main(int argc, char* argv[])
  88. {
  89. signal(SIGINT, signalExit);
  90. signal(SIGTERM, signalExit);
  91.  
  92. MyBackground object;
  93.  
  94. Lock lock{g_exitMutex};
  95. g_exitCondition.wait(lock, [](){return g_exitFlag;});
  96.  
  97. // here ther's some async background work
  98. return EXIT_SUCCESS;
  99.  
  100. // ~MyBackground -> here threads are stopped
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement