juce_CriticalSection.h 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. //==============================================================================
  20. /**
  21. A re-entrant mutex.
  22. A CriticalSection acts as a re-entrant mutex object. The best way to lock and unlock
  23. one of these is by using RAII in the form of a local ScopedLock object - have a look
  24. through the codebase for many examples of how to do this.
  25. In almost all cases you'll want to declare your CriticalSection as a member variable.
  26. Occasionally you may want to declare one as a static variable, but in that case the usual
  27. C++ static object order-of-construction warnings should be heeded.
  28. @see ScopedLock, ScopedTryLock, ScopedUnlock, SpinLock, ReadWriteLock, Thread, InterProcessLock
  29. @tags{Core}
  30. */
  31. class JUCE_API CriticalSection
  32. {
  33. public:
  34. //==============================================================================
  35. /** Creates a CriticalSection object. */
  36. CriticalSection() noexcept;
  37. /** Destructor.
  38. If the critical section is deleted whilst locked, any subsequent behaviour
  39. is unpredictable.
  40. */
  41. ~CriticalSection() noexcept;
  42. //==============================================================================
  43. /** Acquires the lock.
  44. If the lock is already held by the caller thread, the method returns immediately.
  45. If the lock is currently held by another thread, this will wait until it becomes free.
  46. It's strongly recommended that you never call this method directly - instead use the
  47. ScopedLock class to manage the locking using an RAII pattern instead.
  48. @see exit, tryEnter, ScopedLock
  49. */
  50. void enter() const noexcept;
  51. /** Attempts to lock this critical section without blocking.
  52. This method behaves identically to CriticalSection::enter, except that the caller thread
  53. does not wait if the lock is currently held by another thread but returns false immediately.
  54. @returns false if the lock is currently held by another thread, true otherwise.
  55. @see enter
  56. */
  57. bool tryEnter() const noexcept;
  58. /** Releases the lock.
  59. If the caller thread hasn't got the lock, this can have unpredictable results.
  60. If the enter() method has been called multiple times by the thread, each
  61. call must be matched by a call to exit() before other threads will be allowed
  62. to take over the lock.
  63. @see enter, ScopedLock
  64. */
  65. void exit() const noexcept;
  66. //==============================================================================
  67. /** Provides the type of scoped lock to use with a CriticalSection. */
  68. using ScopedLockType = GenericScopedLock<CriticalSection>;
  69. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  70. using ScopedUnlockType = GenericScopedUnlock<CriticalSection>;
  71. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  72. using ScopedTryLockType = GenericScopedTryLock<CriticalSection>;
  73. private:
  74. //==============================================================================
  75. #if JUCE_WINDOWS
  76. // To avoid including windows.h in the public JUCE headers, we'll just allocate
  77. // a block of memory here that's big enough to be used internally as a windows
  78. // CRITICAL_SECTION structure.
  79. #if JUCE_64BIT
  80. uint8 lock[44];
  81. #else
  82. uint8 lock[24];
  83. #endif
  84. #else
  85. mutable pthread_mutex_t lock;
  86. #endif
  87. JUCE_DECLARE_NON_COPYABLE (CriticalSection)
  88. };
  89. //==============================================================================
  90. /**
  91. A class that can be used in place of a real CriticalSection object, but which
  92. doesn't perform any locking.
  93. This is currently used by some templated classes, and most compilers should
  94. manage to optimise it out of existence.
  95. @see CriticalSection, Array, OwnedArray, ReferenceCountedArray
  96. @tags{Core}
  97. */
  98. class JUCE_API DummyCriticalSection
  99. {
  100. public:
  101. inline DummyCriticalSection() = default;
  102. inline ~DummyCriticalSection() = default;
  103. inline void enter() const noexcept {}
  104. inline bool tryEnter() const noexcept { return true; }
  105. inline void exit() const noexcept {}
  106. //==============================================================================
  107. /** A dummy scoped-lock type to use with a dummy critical section. */
  108. struct ScopedLockType
  109. {
  110. ScopedLockType (const DummyCriticalSection&) noexcept {}
  111. };
  112. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  113. using ScopedUnlockType = ScopedLockType;
  114. private:
  115. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection)
  116. };
  117. //==============================================================================
  118. /**
  119. Automatically locks and unlocks a CriticalSection object.
  120. You can use a ScopedLock as a local variable to provide RAII-based locking of a CriticalSection.
  121. e.g. @code
  122. struct MyObject
  123. {
  124. CriticalSection objectLock;
  125. // assuming that this example function will be called by multiple threads
  126. void foo()
  127. {
  128. const ScopedLock myScopedLock (objectLock);
  129. // objectLock is now locked..
  130. ...do some thread-safe work here...
  131. // ..and objectLock gets unlocked here, as myScopedLock goes out of
  132. // scope at the end of the block
  133. }
  134. };
  135. @endcode
  136. @see CriticalSection, ScopedUnlock
  137. */
  138. using ScopedLock = CriticalSection::ScopedLockType;
  139. //==============================================================================
  140. /**
  141. Automatically unlocks and re-locks a CriticalSection object.
  142. This is the reverse of a ScopedLock object - instead of locking the critical
  143. section for the lifetime of this object, it unlocks it.
  144. Make sure you don't try to unlock critical sections that aren't actually locked!
  145. e.g. @code
  146. struct MyObject
  147. {
  148. CriticalSection objectLock;
  149. void foo()
  150. {
  151. {
  152. const ScopedLock myScopedLock (objectLock);
  153. // objectLock is now locked..
  154. {
  155. ScopedUnlock myUnlocker (objectLock);
  156. // ..and now unlocked..
  157. }
  158. // ..and now locked again..
  159. }
  160. // ..and finally unlocked.
  161. }
  162. };
  163. @endcode
  164. @see CriticalSection, ScopedLock
  165. */
  166. using ScopedUnlock = CriticalSection::ScopedUnlockType;
  167. //==============================================================================
  168. /**
  169. Automatically tries to lock and unlock a CriticalSection object.
  170. Use one of these as a local variable to control access to a CriticalSection.
  171. e.g. @code
  172. struct MyObject
  173. {
  174. CriticalSection objectLock;
  175. void foo()
  176. {
  177. const ScopedTryLock myScopedTryLock (objectLock);
  178. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  179. // must call the isLocked() method before making any assumptions..
  180. if (myScopedTryLock.isLocked())
  181. {
  182. ...safely do some work...
  183. }
  184. else
  185. {
  186. // If we get here, then our attempt at locking failed because another thread had already locked it..
  187. }
  188. }
  189. };
  190. @endcode
  191. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  192. */
  193. using ScopedTryLock = CriticalSection::ScopedTryLockType;
  194. } // namespace juce