1/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef SkMutex_DEFINED
9#define SkMutex_DEFINED
10
11#include "include/core/SkTypes.h"
12#include "include/private/SkMacros.h"
13#include "include/private/SkSemaphore.h"
14#include "include/private/SkThreadAnnotations.h"
15#include "include/private/SkThreadID.h"
16
17class SK_CAPABILITY("mutex") SkMutex {
18public:
19 constexpr SkMutex() = default;
20
21 void acquire() SK_ACQUIRE() {
22 fSemaphore.wait();
23 SkDEBUGCODE(fOwner = SkGetThreadID();)
24 }
25
26 void release() SK_RELEASE_CAPABILITY() {
27 this->assertHeld();
28 SkDEBUGCODE(fOwner = kIllegalThreadID;)
29 fSemaphore.signal();
30 }
31
32 void assertHeld() SK_ASSERT_CAPABILITY(this) {
33 SkASSERT(fOwner == SkGetThreadID());
34 }
35
36private:
37 SkSemaphore fSemaphore{1};
38 SkDEBUGCODE(SkThreadID fOwner{kIllegalThreadID};)
39};
40
41class SK_SCOPED_CAPABILITY SkAutoMutexExclusive {
42public:
43 SkAutoMutexExclusive(SkMutex& mutex) SK_ACQUIRE(mutex) : fMutex(mutex) { fMutex.acquire(); }
44 ~SkAutoMutexExclusive() SK_RELEASE_CAPABILITY() { fMutex.release(); }
45
46private:
47 SkMutex& fMutex;
48};
49
50#define SkAutoMutexExclusive(...) SK_REQUIRE_LOCAL_VAR(SkAutoMutexExclusive)
51
52#endif // SkMutex_DEFINED
53