Timer.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include <iostream>
  2. #include <chrono>
  3. #include "Util.h"
  4. #include "Timer.h"
  5. namespace PresenceDetection {
  6. namespace Util {
  7. Timer::Timer() :
  8. m_run(false),
  9. m_aborted(false),
  10. m_identifier(CreateRandomString(10))
  11. {
  12. }
  13. Timer::~Timer()
  14. {
  15. Abort();
  16. Wait();
  17. }
  18. Timer::Timer(Timer&& other) :
  19. m_run(static_cast<bool>(other.m_run)),
  20. m_identifier(other.m_identifier),
  21. m_thread(std::move(other.m_thread))
  22. {
  23. }
  24. Timer& Timer::operator=(Timer&& other)
  25. {
  26. m_run = static_cast<bool>(other.m_run);
  27. m_identifier = std::move(other.m_identifier);
  28. m_thread = std::move(other.m_thread);
  29. return *this;
  30. }
  31. bool Timer::operator==(const Timer& other) const
  32. {
  33. return m_identifier == other.Identifier();
  34. }
  35. bool Timer::operator==(const std::string& identifier) const
  36. {
  37. return m_identifier == identifier;
  38. }
  39. bool Timer::operator==(bool running) const
  40. {
  41. return IsRunning() == running;
  42. }
  43. std::string Timer::Identifier() const
  44. {
  45. return m_identifier;
  46. }
  47. void Timer::Stop()
  48. {
  49. m_run.store(false, std::memory_order_release);
  50. }
  51. void Timer::Abort()
  52. {
  53. std::cout << "Timer::Abort()" << std::endl;
  54. m_run.store(false, std::memory_order_release);
  55. {
  56. std::unique_lock<std::mutex> lock(m_mutex);
  57. m_aborted = true;
  58. }
  59. m_conditionVariable.notify_all();
  60. }
  61. bool Timer::IsRunning() const noexcept
  62. {
  63. return (m_run.load(std::memory_order_acquire) && m_thread.joinable());
  64. }
  65. void Timer::Wait()
  66. {
  67. if (m_thread.joinable())
  68. m_thread.join();
  69. }
  70. } // namespace Util
  71. } // namespace PresenceDetection