fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <atomic>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8. class Alarm {
  9. public:
  10. Alarm(int hour, int minute, std::string speech);
  11. Alarm(const Alarm& other);
  12. Alarm& operator=(const Alarm& other);
  13. void start();
  14. void stop();
  15. bool isStopped() const;
  16. // std::string getStats() const;
  17.  
  18. private:
  19. int m_hour;
  20. int m_minute;
  21. std::string m_speech;
  22. std::atomic<bool> m_stopped;
  23. };
  24.  
  25. Alarm::Alarm(int hour, int minute, string speech)
  26. : m_hour(hour),m_minute(minute),m_speech(speech),m_stopped(false) {
  27. }
  28.  
  29. Alarm::Alarm(const Alarm& other)
  30. : m_hour(other.m_hour),m_minute(other.m_minute),m_speech(other.m_speech),m_stopped(other.isStopped()) {
  31. }
  32. Alarm& Alarm::operator=(const Alarm& other) {
  33. m_hour = other.m_hour;
  34. m_minute = other.m_minute;
  35. m_speech = other.m_speech;
  36. m_stopped.store(other.isStopped());
  37. return *this;
  38. }
  39.  
  40. void Alarm::start() {
  41. int currentHour, currentMinute;
  42.  
  43. while (!Alarm::isStopped()) {
  44. time_t now = time(NULL);
  45. struct tm *current = localtime(&now);
  46.  
  47. currentHour = current->tm_hour;
  48. currentMinute = current->tm_min;
  49.  
  50. if (currentHour == m_hour && currentMinute == m_minute) {
  51. cout << m_speech << endl;
  52. m_stopped.store(true);
  53. }
  54. else {
  55. this_thread::sleep_for(chrono::milliseconds(1000));
  56. }
  57. }
  58. }
  59.  
  60. void Alarm::stop() {
  61. m_stopped.store(true);
  62. }
  63.  
  64. bool Alarm::isStopped() const {
  65. return m_stopped.load();
  66. }
  67.  
  68. int main(int argc, const char * argv[]) {
  69. Alarm test1(12, 12, "foo");
  70. Alarm test2(12, 12, "foo");
  71.  
  72. std::thread t1(&Alarm::start,test1);
  73. std::thread t2(&Alarm::start,test2);
  74.  
  75. bool stop2ndThread = false;
  76. while(!test1.isStopped() && !test2.isStopped()) {
  77. this_thread::sleep_for(chrono::milliseconds(1000));
  78. if(!stop2ndThread) {
  79. test1.stop();
  80. }
  81. else {
  82. test2.stop();
  83. }
  84. }
  85.  
  86. t2.join();
  87. t1.join();
  88. }
Time limit exceeded #stdin #stdout 5s 9616KB
stdin
Standard input is empty
stdout
Standard output is empty