The Pedigree Project  0.1
LockGuard.h
1 /*
2  * Copyright (c) 2008-2014, Pedigree Developers
3  *
4  * Please see the CONTRIB file in the root of the source tree for a full
5  * list of contributors.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #ifndef KERNEL_LOCKGUARD_H
21 #define KERNEL_LOCKGUARD_H
22 
23 #include "pedigree/kernel/compiler.h"
24 
25 class Spinlock;
26 class Mutex;
27 class Semaphore;
28 
32 template <class T>
34 {
35  public:
36  LockGuard(T &Lock, bool Condition = true)
37  : m_Lock(Lock), m_bCondition(Condition)
38  {
39  if (m_bCondition)
40  m_Lock.acquire();
41  }
42  ~LockGuard()
43  {
44  if (m_bCondition)
45  m_Lock.release();
46  }
47 
48  private:
49  LockGuard() = delete;
50  NOT_COPYABLE_OR_ASSIGNABLE(LockGuard);
51 
52  T &m_Lock;
53  bool m_bCondition;
54 };
55 
56 template <class T>
58 {
59  public:
60  RecursingLockGuard(T &Lock, bool Condition = true)
61  : m_Lock(Lock), m_bCondition(Condition)
62  {
63  // T::allow_recursion must exist to be able to use RecursingLockGuard.
64  if (m_bCondition)
65  m_Lock.acquire(T::allow_recursion);
66  }
68  {
69  if (m_bCondition)
70  m_Lock.release();
71  }
72 
73  private:
74  RecursingLockGuard() = delete;
75  NOT_COPYABLE_OR_ASSIGNABLE(RecursingLockGuard);
76 
77  T &m_Lock;
78  bool m_bCondition;
79 };
80 
81 extern template class LockGuard<Spinlock>;
82 extern template class RecursingLockGuard<Spinlock>;
83 #ifdef THREADS
84 extern template class LockGuard<Mutex>;
85 extern template class LockGuard<Semaphore>;
86 #endif
87 
90 #endif
Definition: Mutex.h:58