1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- //
- // Created by zx on 22-12-1.
- //
- #ifndef LIO_LIVOX_CPP_DEFINE_TIME_DATA_H_
- #define LIO_LIVOX_CPP_DEFINE_TIME_DATA_H_
- #include <chrono>
- #include <mutex>
- template <typename T>
- class TimedLockData
- {
- public:
- TimedLockData();
- void reset(const T& tdata,double timeout=0.1);
- bool timeout();
- T Get();
- protected:
- T data_;
- std::chrono::steady_clock::time_point tp_;
- std::mutex mutex_;
- double timeout_;
- };
- template <typename T>
- TimedLockData<T>::TimedLockData()
- {
- timeout_=0.1;
- }
- template <typename T>
- void TimedLockData<T>::reset(const T& tdata,double timeout)
- {
- std::lock_guard<std::mutex> lck (mutex_);
- data_=tdata;
- timeout_=timeout;
- tp_=std::chrono::steady_clock::now();
- }
- template <typename T>
- bool TimedLockData<T>::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>::Get()
- {
- std::lock_guard<std::mutex> lck (mutex_);
- return data_;
- }
- #endif //LIO_LIVOX_CPP_DEFINE_TIME_DATA_H_
|