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 // 未テスト
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     // 初期化不要
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         // カウンタの符号を正に設定することでロックを解除します。
88         ReverseUpdater updater;
89         m_Counter->AtomicUpdateConditional(updater);
90 
91         // 待機している最も優先度の高いスレッドを起床します。
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