eathread_mutex.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Copyright (c) Electronic Arts Inc. All rights reserved.
  3. ///////////////////////////////////////////////////////////////////////////////
  4. /////////////////////////////////////////////////////////////////////////////
  5. // Implements a lightweight mutex.
  6. /////////////////////////////////////////////////////////////////////////////
  7. // TODO(rparolin): Consider adding support for static thread safety analysis.
  8. // https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
  9. #ifndef EATHREAD_EATHREAD_MUTEX_H
  10. #define EATHREAD_EATHREAD_MUTEX_H
  11. #if defined(EA_COMPILER_MSVC)
  12. #include <math.h> // #include math.h because VC++ has a header file but that requires math.h to be #included before some other headers, lest you get a warning.
  13. #endif
  14. #include <stddef.h>
  15. #include <eathread/internal/config.h>
  16. #include <eathread/eathread.h>
  17. #if defined(EA_PRAGMA_ONCE_SUPPORTED)
  18. #pragma once // Some compilers (e.g. VC++) benefit significantly from using this. We've measured 3-4% build speed improvements in apps as a result.
  19. #endif
  20. /////////////////////////////////////////////////////////////////////////
  21. /// EAMutexData
  22. ///
  23. /// This is used internally by class Mutex.
  24. /// Todo: Consider moving this declaration into a platform-specific
  25. /// header file.
  26. ///
  27. #if !EA_THREADS_AVAILABLE
  28. #define EA_THREAD_NONTHREADED_MUTEX 1
  29. struct EAMutexData
  30. {
  31. int mnLockCount;
  32. EAMutexData();
  33. };
  34. #elif EA_USE_CPP11_CONCURRENCY
  35. EA_DISABLE_ALL_VC_WARNINGS()
  36. #include <mutex>
  37. EA_RESTORE_ALL_VC_WARNINGS()
  38. #if defined EA_PLATFORM_MICROSOFT
  39. #ifdef CreateMutex
  40. #undef CreateMutex // Windows #defines CreateMutex to CreateMutexA or CreateMutexW.
  41. #endif
  42. #endif
  43. struct EAMutexData
  44. {
  45. std::recursive_timed_mutex mMutex;
  46. int mnLockCount;
  47. #if EAT_ASSERT_ENABLED
  48. EA::Thread::ThreadId mThreadId; // This value is only valid in debug builds.
  49. #endif
  50. EAMutexData();
  51. private:
  52. EAMutexData(const EAMutexData&);
  53. EAMutexData& operator=(const EAMutexData&);
  54. };
  55. #elif defined(EA_PLATFORM_SONY)
  56. #include <kernel.h>
  57. #include <eathread/internal/timings.h>
  58. struct EAMutexData
  59. {
  60. ScePthreadMutex mMutex;
  61. int mnLockCount;
  62. #if EAT_ASSERT_ENABLED
  63. EA::Thread::ThreadId mThreadId; // This value is only valid in debug builds.
  64. #endif
  65. EAMutexData();
  66. void SimulateLock(bool bLock);
  67. };
  68. #elif defined(EA_PLATFORM_UNIX) || EA_POSIX_THREADS_AVAILABLE
  69. #include <pthread.h>
  70. #if defined(EA_PLATFORM_WINDOWS)
  71. #ifdef CreateMutex
  72. #undef CreateMutex // Windows #defines CreateMutex to CreateMutexA or CreateMutexW.
  73. #endif
  74. #endif
  75. struct EAMutexData
  76. {
  77. pthread_mutex_t mMutex;
  78. int mnLockCount;
  79. #if EAT_ASSERT_ENABLED
  80. EA::Thread::ThreadId mThreadId; // This value is only valid in debug builds.
  81. #endif
  82. EAMutexData();
  83. void SimulateLock(bool bLock);
  84. };
  85. #elif defined(EA_PLATFORM_MICROSOFT) && !EA_POSIX_THREADS_AVAILABLE
  86. #ifdef EA_PROCESSOR_X86_64
  87. static const int MUTEX_PLATFORM_DATA_SIZE = 40; // CRITICAL_SECTION is 40 bytes on Win64.
  88. #else
  89. static const int MUTEX_PLATFORM_DATA_SIZE = 32; // CRITICAL_SECTION is 24 bytes on Win32, 28 bytes on XBox 360.
  90. #endif
  91. #ifdef CreateMutex
  92. #undef CreateMutex // Windows #defines CreateMutex to CreateMutexA or CreateMutexW.
  93. #endif
  94. struct EATHREADLIB_API EAMutexData
  95. {
  96. uint64_t mData[MUTEX_PLATFORM_DATA_SIZE / sizeof(uint64_t)]; // Holds either CRITICAL_SECTION or HANDLE if mbIntraProcess is true or false, respectively.
  97. int mnLockCount;
  98. bool mbIntraProcess;
  99. #if EAT_ASSERT_ENABLED
  100. EA::Thread::ThreadId mThreadId; // This value is only valid in debug builds.
  101. EA::Thread::SysThreadId mSysThreadId; // This value is only valid in debug builds.
  102. #endif
  103. EAMutexData();
  104. };
  105. #else
  106. #define EA_THREAD_NONTHREADED_MUTEX 1
  107. struct EAMutexData
  108. {
  109. int mnLockCount;
  110. EAMutexData();
  111. };
  112. #endif
  113. /////////////////////////////////////////////////////////////////////////
  114. namespace EA
  115. {
  116. namespace Thread
  117. {
  118. /// MutexParameters
  119. /// Specifies mutex settings.
  120. struct EATHREADLIB_API MutexParameters
  121. {
  122. bool mbIntraProcess; /// True if the mutex is intra-process, else inter-process.
  123. char mName[128]; /// Mutex name, applicable only to platforms that recognize named synchronization objects.
  124. MutexParameters(bool bIntraProcess = true, const char* pName = NULL);
  125. };
  126. /// class Mutex
  127. ///
  128. /// Mutex are assumed to always be 'recursive', meaning that a given thread
  129. /// can lock the mutex more than once. If you want a specifically non-recursive
  130. /// mutex, you can use a semaphore with a lock count of 1.
  131. class EATHREADLIB_API Mutex
  132. {
  133. public:
  134. enum Result
  135. {
  136. kResultError = -1,
  137. kResultTimeout = -2
  138. };
  139. /// Mutex
  140. /// For immediate default initialization, use no args.
  141. /// For custom immediate initialization, supply a first argument.
  142. /// For deferred initialization, use Mutex(NULL, false) then later call Init.
  143. /// For deferred initialization of an array of objects, create an empty
  144. /// subclass whose default constructor chains back to Mutex(NULL, false).
  145. Mutex(const MutexParameters* pMutexParameters = NULL, bool bDefaultParameters = true);
  146. /// ~Mutex
  147. /// Destroys an existing mutex. The mutex must not be locked by any thread,
  148. /// otherwise the resulting behaviour is undefined.
  149. ~Mutex();
  150. /// Init
  151. /// Initializes the mutex if not done so in the constructor.
  152. /// This should only be called in the case that this class was constructed
  153. /// with RWMutex(NULL, false).
  154. bool Init(const MutexParameters* pMutexParameters);
  155. /// Lock
  156. /// Locks the mutex, with a timeout specified. This function will
  157. /// return immediately if the mutex is not locked or if the calling
  158. /// thread already has it locked at least once. If the mutex is
  159. /// locked by another thread, this function will block until the mutex
  160. /// is unlocked by the owning thread or until the timeout time has
  161. /// passed. This function may return before the specified timeout has passed
  162. /// and so should not be implicitly used as a timer. Some platforms may
  163. /// return immediately if the timeout is specified as anything but kTimeoutNone.
  164. ///
  165. /// Note that the timeout is specified in absolute time and not relative time.
  166. ///
  167. /// Note also that due to the way thread scheduling works -- particularly in a
  168. /// time-sliced threading environment -- that the timeout value is a hint and
  169. /// the actual amount of time passed before the timeout occurs may be significantly
  170. /// more or less than the specified timeout time.
  171. ///
  172. /// Return value:
  173. /// kResultError Error
  174. /// kResultTimeout Timeout
  175. /// > 0 The new lock count.
  176. int Lock(const ThreadTime& timeoutAbsolute = EA::Thread::kTimeoutNone);
  177. /// Unlock
  178. /// Unlocks the mutex. The mutex must already be locked at least once by
  179. /// the calling thread. Otherwise the behaviour is not defined.
  180. /// Return value is the lock count value immediately upon unlock.
  181. int Unlock();
  182. /// GetLockCount
  183. /// Returns the number of locks on the mutex. The return value from this
  184. /// function is only reliable if the calling thread already has one lock on
  185. /// the critical section. Otherwise the value could be changing as other
  186. /// threads lock or unlock the mutex soon after the call.
  187. /// This function is useful in debugging and asserting and useful for backing
  188. /// out of recursive locks under the case of exceptions and other abortive
  189. /// situations. This function will not necessarily call memory synchronization
  190. /// primitives (e.g. ReadBarrier) itself on systems that require SMP synchronization.
  191. int GetLockCount() const;
  192. /// HasLock
  193. /// Returns true if the current thread has the mutex locked.
  194. /// This function is reliable only in a debug build whereby
  195. /// EAT_ASSERT_ENABLED is defined to 1. This function can thus
  196. /// only be used in debugging situations whereby you want to
  197. /// assert that you have a mutex locked or not. To make this
  198. /// function work in a non-debug environment would necessitate
  199. /// adding an undesirable amount of code and data.
  200. bool HasLock() const;
  201. /// GetPlatformData
  202. /// Returns the platform-specific data handle for debugging uses or
  203. /// other cases whereby special (and non-portable) uses are required.
  204. void* GetPlatformData()
  205. { return &mMutexData; }
  206. protected:
  207. EAMutexData mMutexData;
  208. private:
  209. // Objects of this class are not copyable.
  210. Mutex(const Mutex&){}
  211. Mutex& operator=(const Mutex&){ return *this; }
  212. };
  213. /// MutexFactory
  214. ///
  215. /// Implements a factory-based creation and destruction mechanism for class Mutex.
  216. /// A primary use of this would be to allow the Mutex implementation to reside in
  217. /// a private library while users of the class interact only with the interface
  218. /// header and the factory. The factory provides conventional create/destroy
  219. /// semantics which use global operator new, but also provides manual construction/
  220. /// destruction semantics so that the user can provide for memory allocation
  221. /// and deallocation.
  222. class EATHREADLIB_API MutexFactory
  223. {
  224. public:
  225. static Mutex* CreateMutex(); // Internally implemented as: return new Mutex;
  226. static void DestroyMutex(Mutex* pMutex); // Internally implemented as: delete pMutex;
  227. static size_t GetMutexSize(); // Internally implemented as: return sizeof(Mutex);
  228. static Mutex* ConstructMutex(void* pMemory); // Internally implemented as: return new(pMemory) Mutex;
  229. static void DestructMutex(Mutex* pMutex); // Internally implemented as: pMutex->~Mutex();
  230. };
  231. } // namespace Thread
  232. } // namespace EA
  233. namespace EA
  234. {
  235. namespace Thread
  236. {
  237. /// class AutoMutex
  238. /// An AutoMutex locks the Mutex in its constructor and
  239. /// unlocks the Mutex in its destructor (when it goes out of scope).
  240. class EATHREADLIB_API AutoMutex
  241. {
  242. public:
  243. inline AutoMutex(Mutex& mutex)
  244. : mMutex(mutex)
  245. { mMutex.Lock(); }
  246. inline ~AutoMutex()
  247. { mMutex.Unlock(); }
  248. protected:
  249. Mutex& mMutex;
  250. // Prevent copying by default, as copying is dangerous.
  251. AutoMutex(const AutoMutex&);
  252. const AutoMutex& operator=(const AutoMutex&);
  253. };
  254. } // namespace Thread
  255. } // namespace EA
  256. #endif // EATHREAD_EATHREAD_MUTEX_H