timedlockdata.hpp 1.1 KB

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