summaryrefslogtreecommitdiffstats
path: root/src/common/synchronized_wrapper.h
blob: 4a1984c46e6a88f3605e9a207782264c66759474 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2015 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#pragma once

#include <algorithm>
#include <mutex>

namespace Common {

template <typename T>
class SynchronizedWrapper;

/**
 * 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);
        return *this;
    }

    T& operator*() {
        return wrapper->data;
    }
    const T& operator*() const {
        return wrapper->data;
    }

    T* operator->() {
        return &wrapper->data;
    }
    const T* operator->() const {
        return &wrapper->data;
    }

private:
    SynchronizedWrapper<T>* wrapper;
};

/**
 * 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;
};

} // namespace Common