CriticalSection.h (1810B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef MOZILLA_GFX_CRITICALSECTION_H_ 8 #define MOZILLA_GFX_CRITICALSECTION_H_ 9 10 #ifdef WIN32 11 # include <windows.h> 12 #else 13 # include <pthread.h> 14 # include "mozilla/DebugOnly.h" 15 #endif 16 17 namespace mozilla { 18 namespace gfx { 19 20 #ifdef WIN32 21 22 class CriticalSection { 23 public: 24 CriticalSection() { ::InitializeCriticalSection(&mCriticalSection); } 25 26 ~CriticalSection() { ::DeleteCriticalSection(&mCriticalSection); } 27 28 void Enter() { ::EnterCriticalSection(&mCriticalSection); } 29 30 void Leave() { ::LeaveCriticalSection(&mCriticalSection); } 31 32 protected: 33 CRITICAL_SECTION mCriticalSection; 34 }; 35 36 #else 37 // posix 38 39 class PosixCondvar; 40 class CriticalSection { 41 public: 42 CriticalSection() { 43 DebugOnly<int> err = pthread_mutex_init(&mMutex, nullptr); 44 MOZ_ASSERT(!err); 45 } 46 47 ~CriticalSection() { 48 DebugOnly<int> err = pthread_mutex_destroy(&mMutex); 49 MOZ_ASSERT(!err); 50 } 51 52 void Enter() { 53 DebugOnly<int> err = pthread_mutex_lock(&mMutex); 54 MOZ_ASSERT(!err); 55 } 56 57 void Leave() { 58 DebugOnly<int> err = pthread_mutex_unlock(&mMutex); 59 MOZ_ASSERT(!err); 60 } 61 62 protected: 63 pthread_mutex_t mMutex; 64 friend class PosixCondVar; 65 }; 66 67 #endif 68 69 /// RAII helper. 70 struct CriticalSectionAutoEnter final { 71 explicit CriticalSectionAutoEnter(CriticalSection* aSection) 72 : mSection(aSection) { 73 mSection->Enter(); 74 } 75 ~CriticalSectionAutoEnter() { mSection->Leave(); } 76 77 protected: 78 CriticalSection* mSection; 79 }; 80 81 } // namespace gfx 82 } // namespace mozilla 83 84 #endif