aboutsummaryrefslogtreecommitdiffhomepage
path: root/include/private/SkMutex.h
blob: 7cfdb1132c2f97a1795abc2728b0dcdbbccb3232 (plain)
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
86
87
88
89
90
91
92
93
/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SkMutex_DEFINED
#define SkMutex_DEFINED

#include "../private/SkSemaphore.h"
#include "../private/SkThreadID.h"
#include "SkTypes.h"

#define SK_DECLARE_STATIC_MUTEX(name) static SkBaseMutex name;

class SkBaseMutex {
public:
    constexpr SkBaseMutex() = default;

    void acquire() {
        fSemaphore.wait();
        SkDEBUGCODE(fOwner = SkGetThreadID();)
    }

    void release() {
        this->assertHeld();
        SkDEBUGCODE(fOwner = kIllegalThreadID;)
        fSemaphore.signal();
    }

    void assertHeld() {
        SkASSERT(fOwner == SkGetThreadID());
    }

protected:
    SkBaseSemaphore fSemaphore{1};
    SkDEBUGCODE(SkThreadID fOwner{kIllegalThreadID};)
};

class SkMutex : public SkBaseMutex {
public:
    using SkBaseMutex::SkBaseMutex;
    ~SkMutex() { fSemaphore.cleanup(); }
};

class SkAutoMutexAcquire {
public:
    template <typename T>
    SkAutoMutexAcquire(T* mutex) : fMutex(mutex) {
        if (mutex) {
            mutex->acquire();
        }
        fRelease = [](void* mutex) { ((T*)mutex)->release(); };
    }

    template <typename T>
    SkAutoMutexAcquire(T& mutex) : SkAutoMutexAcquire(&mutex) {}

    ~SkAutoMutexAcquire() { this->release(); }

    void release() {
        if (fMutex) {
            fRelease(fMutex);
        }
        fMutex = nullptr;
    }

private:
    void*  fMutex;
    void (*fRelease)(void*);
};
#define SkAutoMutexAcquire(...) SK_REQUIRE_LOCAL_VAR(SkAutoMutexAcquire)

// SkAutoExclusive is a lighter weight version of SkAutoMutexAcquire.
// It assumes that there is a valid mutex, obviating the null check.
class SkAutoExclusive {
public:
    template <typename T>
    SkAutoExclusive(T& mutex) : fMutex(&mutex) {
        mutex.acquire();

        fRelease = [](void* mutex) { ((T*)mutex)->release(); };
    }
    ~SkAutoExclusive() { fRelease(fMutex); }

private:
    void* fMutex;
    void (*fRelease)(void*);
};
#define SkAutoExclusive(...) SK_REQUIRE_LOCAL_VAR(SkAutoExclusive)

#endif//SkMutex_DEFINED