2015-02-05 22:23:25 +05:30
|
|
|
// Copyright 2015 Citra Emulator Project
|
|
|
|
// Licensed under GPLv2 or any later version
|
|
|
|
// Refer to the license.txt file included.
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2015-06-21 04:06:19 +05:30
|
|
|
#include <algorithm>
|
2015-02-05 22:23:25 +05:30
|
|
|
#include <mutex>
|
|
|
|
|
|
|
|
namespace Common {
|
|
|
|
|
|
|
|
template <typename T>
|
2017-02-19 07:57:37 +05:30
|
|
|
class SynchronizedWrapper;
|
2015-02-05 22:23:25 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
* Synchronized reference, that keeps a SynchronizedWrapper's mutex locked during its lifetime. This
|
|
|
|
* greatly reduces the chance that someone will access the wrapped resource without locking the
|
|
|
|
* mutex.
|
|
|
|
*/
|
|
|
|
template <typename T>
|
|
|
|
class SynchronizedRef {
|
|
|
|
public:
|
|
|
|
SynchronizedRef(SynchronizedWrapper<T>& wrapper) : wrapper(&wrapper) {
|
|
|
|
wrapper.mutex.lock();
|
|
|
|
}
|
|
|
|
|
|
|
|
SynchronizedRef(SynchronizedRef&) = delete;
|
|
|
|
SynchronizedRef(SynchronizedRef&& o) : wrapper(o.wrapper) {
|
|
|
|
o.wrapper = nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
~SynchronizedRef() {
|
|
|
|
if (wrapper)
|
|
|
|
wrapper->mutex.unlock();
|
|
|
|
}
|
|
|
|
|
|
|
|
SynchronizedRef& operator=(SynchronizedRef&) = delete;
|
|
|
|
SynchronizedRef& operator=(SynchronizedRef&& o) {
|
|
|
|
std::swap(wrapper, o.wrapper);
|
2015-09-12 07:30:21 +05:30
|
|
|
return *this;
|
2015-02-05 22:23:25 +05:30
|
|
|
}
|
|
|
|
|
2016-09-18 06:08:01 +05:30
|
|
|
T& operator*() {
|
|
|
|
return wrapper->data;
|
|
|
|
}
|
|
|
|
const T& operator*() const {
|
|
|
|
return wrapper->data;
|
|
|
|
}
|
2015-02-05 22:23:25 +05:30
|
|
|
|
2016-09-18 06:08:01 +05:30
|
|
|
T* operator->() {
|
|
|
|
return &wrapper->data;
|
|
|
|
}
|
|
|
|
const T* operator->() const {
|
|
|
|
return &wrapper->data;
|
|
|
|
}
|
2015-02-05 22:23:25 +05:30
|
|
|
|
|
|
|
private:
|
|
|
|
SynchronizedWrapper<T>* wrapper;
|
|
|
|
};
|
|
|
|
|
2017-02-19 07:57:37 +05:30
|
|
|
/**
|
|
|
|
* Wraps an object, only allowing access to it via a locking reference wrapper. Good to ensure no
|
|
|
|
* one forgets to lock a mutex before acessing an object. To access the wrapped object construct a
|
|
|
|
* SyncronizedRef on this wrapper. Inspired by Rust's Mutex type
|
|
|
|
* (http://doc.rust-lang.org/std/sync/struct.Mutex.html).
|
|
|
|
*/
|
|
|
|
template <typename T>
|
|
|
|
class SynchronizedWrapper {
|
|
|
|
public:
|
|
|
|
template <typename... Args>
|
|
|
|
SynchronizedWrapper(Args&&... args) : data(std::forward<Args>(args)...) {}
|
|
|
|
|
|
|
|
SynchronizedRef<T> Lock() {
|
|
|
|
return {*this};
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
template <typename U>
|
|
|
|
friend class SynchronizedRef;
|
|
|
|
|
|
|
|
std::mutex mutex;
|
|
|
|
T data;
|
|
|
|
};
|
|
|
|
|
2015-02-05 22:23:25 +05:30
|
|
|
} // namespace Common
|