herb | ac09471 | 2015-07-09 13:44:32 -0700 | [diff] [blame] | 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 | |
mtklein | a64c48f | 2015-01-21 13:13:31 -0800 | [diff] [blame] | 8 | #ifndef SkMutex_DEFINED |
| 9 | #define SkMutex_DEFINED |
| 10 | |
Mike Klein | c0bd9f9 | 2019-04-23 12:05:21 -0500 | [diff] [blame] | 11 | #include "include/core/SkTypes.h" |
| 12 | #include "include/private/SkMacros.h" |
| 13 | #include "include/private/SkSemaphore.h" |
Herb Derby | 9b86955 | 2019-05-10 12:16:17 -0400 | [diff] [blame] | 14 | #include "include/private/SkThreadAnnotations.h" |
Mike Klein | c0bd9f9 | 2019-04-23 12:05:21 -0500 | [diff] [blame] | 15 | #include "include/private/SkThreadID.h" |
mtklein | a64c48f | 2015-01-21 13:13:31 -0800 | [diff] [blame] | 16 | |
Herb Derby | 9b86955 | 2019-05-10 12:16:17 -0400 | [diff] [blame] | 17 | class SK_CAPABILITY("mutex") SkMutex { |
sclittle | d9f5d20 | 2016-05-04 18:23:30 -0700 | [diff] [blame] | 18 | public: |
Herb Derby | 9b86955 | 2019-05-10 12:16:17 -0400 | [diff] [blame] | 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 | |
| 36 | private: |
| 37 | SkSemaphore fSemaphore{1}; |
| 38 | SkDEBUGCODE(SkThreadID fOwner{kIllegalThreadID};) |
herb | 7f0a3d7 | 2015-09-24 07:34:49 -0700 | [diff] [blame] | 39 | }; |
mtklein | a64c48f | 2015-01-21 13:13:31 -0800 | [diff] [blame] | 40 | |
Herb Derby | 9b86955 | 2019-05-10 12:16:17 -0400 | [diff] [blame] | 41 | class SK_SCOPED_CAPABILITY SkAutoMutexExclusive { |
mtklein | f10637f | 2016-06-10 13:56:35 -0700 | [diff] [blame] | 42 | public: |
Herb Derby | 9b86955 | 2019-05-10 12:16:17 -0400 | [diff] [blame] | 43 | SkAutoMutexExclusive(SkMutex& mutex) SK_ACQUIRE(mutex) : fMutex(mutex) { fMutex.acquire(); } |
| 44 | ~SkAutoMutexExclusive() SK_RELEASE_CAPABILITY() { fMutex.release(); } |
mtklein | f10637f | 2016-06-10 13:56:35 -0700 | [diff] [blame] | 45 | |
| 46 | private: |
Herb Derby | 9b86955 | 2019-05-10 12:16:17 -0400 | [diff] [blame] | 47 | SkMutex& fMutex; |
mtklein | f10637f | 2016-06-10 13:56:35 -0700 | [diff] [blame] | 48 | }; |
Herb Derby | 9b86955 | 2019-05-10 12:16:17 -0400 | [diff] [blame] | 49 | |
| 50 | #define SkAutoMutexExclusive(...) SK_REQUIRE_LOCAL_VAR(SkAutoMutexExclusive) |
herb | 12449a9 | 2015-10-21 19:11:13 -0700 | [diff] [blame] | 51 | |
Herb Derby | 9c71e7b | 2019-06-17 14:40:42 -0400 | [diff] [blame] | 52 | #endif // SkMutex_DEFINED |