2020-02-12 10:28:27 +00:00
|
|
|
//
|
|
|
|
// Created by loki on 16-4-19.
|
|
|
|
//
|
|
|
|
|
|
|
|
#ifndef SUNSHINE_SYNC_H
|
|
|
|
#define SUNSHINE_SYNC_H
|
|
|
|
|
|
|
|
#include <utility>
|
|
|
|
#include <mutex>
|
|
|
|
#include <array>
|
|
|
|
|
|
|
|
namespace util {
|
|
|
|
|
2020-03-14 13:38:09 +00:00
|
|
|
template<class T, class M = std::mutex>
|
2020-02-12 10:28:27 +00:00
|
|
|
class sync_t {
|
|
|
|
public:
|
2020-03-14 13:38:09 +00:00
|
|
|
using value_t = T;
|
|
|
|
using mutex_t = M;
|
2020-02-12 10:28:27 +00:00
|
|
|
|
2020-03-14 13:38:09 +00:00
|
|
|
std::lock_guard<mutex_t> lock() {
|
|
|
|
return std::lock_guard { _lock };
|
2020-02-12 10:28:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
template<class ...Args>
|
|
|
|
sync_t(Args&&... args) : raw {std::forward<Args>(args)... } {}
|
|
|
|
|
|
|
|
sync_t &operator=(sync_t &&other) noexcept {
|
2020-03-14 13:38:09 +00:00
|
|
|
std::lock(_lock, other._lock);
|
2020-02-12 10:28:27 +00:00
|
|
|
|
|
|
|
raw = std::move(other.raw);
|
|
|
|
|
2020-03-14 13:38:09 +00:00
|
|
|
_lock.unlock();
|
|
|
|
other._lock.unlock();
|
2020-02-12 10:28:27 +00:00
|
|
|
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
|
|
|
sync_t &operator=(sync_t &other) noexcept {
|
2020-03-14 13:38:09 +00:00
|
|
|
std::lock(_lock, other._lock);
|
2020-02-12 10:28:27 +00:00
|
|
|
|
|
|
|
raw = other.raw;
|
|
|
|
|
2020-03-14 13:38:09 +00:00
|
|
|
_lock.unlock();
|
|
|
|
other._lock.unlock();
|
2020-02-12 10:28:27 +00:00
|
|
|
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2020-03-14 13:38:09 +00:00
|
|
|
sync_t &operator=(const value_t &val) noexcept {
|
|
|
|
auto lg = lock();
|
2020-02-12 10:28:27 +00:00
|
|
|
|
|
|
|
raw = val;
|
|
|
|
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2020-03-14 13:38:09 +00:00
|
|
|
sync_t &operator=(value_t &&val) noexcept {
|
|
|
|
auto lg = lock();
|
2020-02-12 10:28:27 +00:00
|
|
|
|
|
|
|
raw = std::move(val);
|
|
|
|
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2020-03-14 13:38:09 +00:00
|
|
|
value_t *operator->() {
|
2020-02-12 10:28:27 +00:00
|
|
|
return &raw;
|
|
|
|
}
|
|
|
|
|
2020-03-14 13:38:09 +00:00
|
|
|
value_t &operator*() {
|
|
|
|
return raw;
|
|
|
|
}
|
|
|
|
|
|
|
|
const value_t &operator*() const {
|
|
|
|
return raw;
|
|
|
|
}
|
|
|
|
|
|
|
|
value_t raw;
|
2020-02-12 10:28:27 +00:00
|
|
|
private:
|
2020-03-14 13:38:09 +00:00
|
|
|
mutex_t _lock;
|
2020-02-12 10:28:27 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#endif //T_MAN_SYNC_H
|