12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- //
- // Created by zx on 22-12-1.
- //
- #pragma once
- #include <chrono>
- #include <mutex>
- template <typename T>
- class TimedLockData
- {
- public:
- TimedLockData();
- TimedLockData<T>& operator=(const T& data);
- bool timeout(const double &timeout = 0.2);
- T operator()(void);
- protected:
- T data_;
- std::chrono::steady_clock::time_point tp_;
- std::mutex mutex_;
- };
- template <typename T>
- TimedLockData<T>::TimedLockData()
- {
- }
- template <typename T>
- TimedLockData<T>& TimedLockData<T>::operator=(const T& data){
- std::lock_guard<std::mutex> lck (mutex_);
- data_=data;
- tp_=std::chrono::steady_clock::now();
- return *this;
- }
- template <typename T>
- bool TimedLockData<T>::timeout(const double &timeout)
- {
- auto now=std::chrono::steady_clock::now();
- auto duration = std::chrono::duration_cast<std::chrono::microseconds>(now - tp_);
- double time = double(duration.count()) * std::chrono::microseconds::period::num / std::chrono::microseconds::period::den;
- return time>timeout;
- }
- template <typename T>
- T TimedLockData<T>::operator()(void)
- {
- std::lock_guard<std::mutex> lck (mutex_);
- return data_;
- }
|