48 lines
1.3 KiB
C++
48 lines
1.3 KiB
C++
#pragma once
|
|
#include "TimeStamp.h"
|
|
#include <atomic>
|
|
#include <tuple>
|
|
|
|
namespace bts {
|
|
namespace utils {
|
|
|
|
template <class T> class Optimistic {
|
|
std::atomic<TimeStamp> _time;
|
|
T _data;
|
|
|
|
public:
|
|
Optimistic() : _time(TimeStamp(0)), _data(T()) {}
|
|
|
|
void store(const T &t) { store(t, TimeStamp::now()); }
|
|
void store(const T &t, TimeStamp time) {
|
|
_time.store(TimeStamp::invalid(), std::memory_order_release);
|
|
_data = t;
|
|
_time.store(time, std::memory_order_release);
|
|
}
|
|
|
|
std::tuple<TimeStamp, T> load() const {
|
|
TimeStamp temp;
|
|
T result;
|
|
int attempts = 0;
|
|
const int max_attempts = 1619200;
|
|
do {
|
|
++attempts;
|
|
temp = _time;
|
|
result = _data;
|
|
} while ((temp != _time || temp == TimeStamp::invalid()) &&
|
|
attempts < max_attempts);
|
|
if (attempts >= max_attempts)
|
|
return std::make_tuple(TimeStamp::invalid(), result);
|
|
return std::make_tuple(temp, result);
|
|
}
|
|
bool load_if_new(TimeStamp &time, T &result) const {
|
|
if (_time > time || _time == TimeStamp::invalid()) {
|
|
std::tie(time, result) = load();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
};
|
|
|
|
} // namespace utils
|
|
} // namespace bts
|