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 17 class SK_CAPABILITY("mutex") SkMutex { 18 public: 19 constexpr SkMutex() = default; 20 acquire()21 void acquire() SK_ACQUIRE() { 22 fSemaphore.wait(); 23 SkDEBUGCODE(fOwner = SkGetThreadID();) 24 } 25 release()26 void release() SK_RELEASE_CAPABILITY() { 27 this->assertHeld(); 28 SkDEBUGCODE(fOwner = kIllegalThreadID;) 29 fSemaphore.signal(); 30 } 31 assertHeld()32 void assertHeld() SK_ASSERT_CAPABILITY(this) { 33 SkASSERT(fOwner == SkGetThreadID()); 34 } 35 36 private: 37 SkSemaphore fSemaphore{1}; 38 SkDEBUGCODE(SkThreadID fOwner{kIllegalThreadID};) 39 }; 40 41 class SK_SCOPED_CAPABILITY SkAutoMutexExclusive { 42 public: SkAutoMutexExclusive(SkMutex & mutex)43 SkAutoMutexExclusive(SkMutex& mutex) SK_ACQUIRE(mutex) : fMutex(mutex) { fMutex.acquire(); } SK_RELEASE_CAPABILITY()44 ~SkAutoMutexExclusive() SK_RELEASE_CAPABILITY() { fMutex.release(); } 45 46 SkAutoMutexExclusive(const SkAutoMutexExclusive&) = delete; 47 SkAutoMutexExclusive(SkAutoMutexExclusive&&) = delete; 48 49 SkAutoMutexExclusive& operator=(const SkAutoMutexExclusive&) = delete; 50 SkAutoMutexExclusive& operator=(SkAutoMutexExclusive&&) = delete; 51 52 private: 53 SkMutex& fMutex; 54 }; 55 56 #endif // SkMutex_DEFINED 57