timedlockdata.hpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // Created by zx on 22-12-1.
  3. //
  4. #ifndef LIO_LIVOX_CPP_DEFINE_TIME_DATA_H_
  5. #define LIO_LIVOX_CPP_DEFINE_TIME_DATA_H_
  6. #include <chrono>
  7. #include <mutex>
  8. template <typename T>
  9. class TimedLockData
  10. {
  11. public:
  12. TimedLockData();
  13. void reset(const T& tdata,double timeout=0.1);
  14. bool timeout();
  15. T Get();
  16. protected:
  17. T data_;
  18. std::chrono::steady_clock::time_point tp_;
  19. std::mutex mutex_;
  20. double timeout_;
  21. };
  22. template <typename T>
  23. TimedLockData<T>::TimedLockData()
  24. {
  25. timeout_=0.1;
  26. }
  27. template <typename T>
  28. void TimedLockData<T>::reset(const T& tdata,double timeout)
  29. {
  30. std::lock_guard<std::mutex> lck (mutex_);
  31. data_=tdata;
  32. timeout_=timeout;
  33. tp_=std::chrono::steady_clock::now();
  34. }
  35. template <typename T>
  36. bool TimedLockData<T>::timeout()
  37. {
  38. auto now=std::chrono::steady_clock::now();
  39. auto duration = std::chrono::duration_cast<std::chrono::microseconds>(now - tp_);
  40. double time = double(duration.count()) * std::chrono::microseconds::period::num / std::chrono::microseconds::period::den;
  41. return time>timeout_;
  42. }
  43. template <typename T>
  44. T TimedLockData<T>::Get()
  45. {
  46. std::lock_guard<std::mutex> lck (mutex_);
  47. return data_;
  48. }
  49. #endif //LIO_LIVOX_CPP_DEFINE_TIME_DATA_H_