1 /*---------------------------------------------------------------------------* 2 Project: Horizon 3 File: os_CriticalSection.h 4 5 Copyright (C)2009 Nintendo Co., Ltd. All rights reserved. 6 7 These coded instructions, statements, and computer programs contain 8 proprietary information of Nintendo of America Inc. and/or Nintendo 9 Company Ltd., and are protected by Federal copyright law. They may 10 not be disclosed to third parties or copied or duplicated in any form, 11 in whole or in part, without the prior written consent of Nintendo. 12 13 $Rev: 20477 $ 14 *---------------------------------------------------------------------------*/ 15 16 #ifndef NN_OS_OS_NONRECURSIVECRITICALSECTION_H_ 17 #define NN_OS_OS_NONRECURSIVECRITICALSECTION_H_ 18 19 #include <nn/os/os_WaitableCounter.h> 20 #include <nn/assert.h> 21 #include <nn/WithInitialize.h> 22 #include <nn/util/detail/util_ScopedLockImpl.h> 23 24 #ifdef __cplusplus 25 26 // Untested 27 28 namespace nn { namespace os { 29 30 class NonRecursiveCriticalSection : private nn::util::NonCopyable<CriticalSection> 31 { 32 private: 33 struct ReverseIfPositiveUpdater 34 { operatorReverseIfPositiveUpdater35 bool operator()(s32& x) 36 { 37 if( x > 0 ) 38 { 39 x = -x; 40 return true; 41 } 42 else 43 { 44 return false; 45 } 46 } 47 }; 48 49 struct ReverseUpdater 50 { 51 s32 afterUpdate; operatorReverseUpdater52 bool operator()(s32& x) 53 { 54 x = -x; 55 afterUpdate = x; 56 return true; 57 } 58 }; 59 60 public: 61 62 static const bool CAN_LOCK_RECURSIVELY = false; 63 64 // No initialization needed NonRecursiveCriticalSection()65 NonRecursiveCriticalSection() { *m_Counter = 1; } 66 ~NonRecursiveCriticalSection()67 ~NonRecursiveCriticalSection() {} 68 Enter()69 void Enter() 70 { 71 while (!TryEnter()) 72 { 73 m_Counter.DecrementAndWaitIfLessThan(0); 74 } 75 } 76 TryEnter()77 bool TryEnter() 78 { 79 ReverseIfPositiveUpdater updater; 80 return m_Counter->AtomicUpdateConditional(updater); 81 } 82 Leave()83 void Leave() 84 { 85 NN_TASSERTMSG_( *m_Counter < 0 , "CriticalSection is not entered."); 86 87 // Unlock by setting the counter's sign to positive. 88 ReverseUpdater updater; 89 m_Counter->AtomicUpdateConditional(updater); 90 91 // Wake the waiting thread that has the highest priority. 92 if( updater.afterUpdate > 1 ) 93 { 94 m_Counter.Signal(1); 95 } 96 } 97 98 class ScopedLock; 99 100 private: 101 nn::os::WaitableCounter m_Counter; 102 }; 103 104 NN_UTIL_DETAIL_DEFINE_SCOPED_LOCK(NonRecursiveCriticalSection, Enter(), Leave()); 105 106 }} 107 108 #endif // __cplusplus 109 110 #endif 111