eathread_rwmutex_ip.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Copyright (c) Electronic Arts Inc. All rights reserved.
  3. ///////////////////////////////////////////////////////////////////////////////
  4. /////////////////////////////////////////////////////////////////////////////
  5. // Implements an interprocess mutex with multiple reads but single writer.
  6. // This allows for high performance systems whereby the consumers of mpData
  7. // are more common than the producers of mpData.
  8. /////////////////////////////////////////////////////////////////////////////
  9. #ifndef EATHREAD_EATHREAD_RWMUTEX_IP_H
  10. #define EATHREAD_EATHREAD_RWMUTEX_IP_H
  11. #include <EABase/eabase.h>
  12. #include <eathread/eathread.h>
  13. #include <new>
  14. #if EA_WINAPI_FAMILY_PARTITION(EA_WINAPI_PARTITION_DESKTOP)
  15. EA_DISABLE_ALL_VC_WARNINGS()
  16. #include <Windows.h>
  17. EA_RESTORE_ALL_VC_WARNINGS()
  18. #endif
  19. #if defined(EA_PRAGMA_ONCE_SUPPORTED)
  20. #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.
  21. #endif
  22. // We have to be careful about disabling this warning. Sometimes the warning is meaningful; sometimes it isn't.
  23. // 4251: class (some template) needs to have dll-interface to be used by clients.
  24. // 6054: String 'argument 2' might not be zero-terminated
  25. EA_DISABLE_VC_WARNING(4251 6054)
  26. namespace EA
  27. {
  28. namespace Thread
  29. {
  30. #if EA_WINAPI_FAMILY_PARTITION(EA_WINAPI_PARTITION_DESKTOP)
  31. template<typename T>
  32. class Shared
  33. {
  34. public:
  35. Shared();
  36. Shared(const char* pName);
  37. ~Shared();
  38. bool Init(const char* pName);
  39. void Shutdown();
  40. bool IsNew() const { return mbCreated; }
  41. T* operator->() { return static_cast<T*>(mpData); }
  42. protected:
  43. uint32_t& GetRefCount();
  44. Shared(const Shared&);
  45. Shared& operator=(const Shared&);
  46. protected:
  47. HANDLE mMapping;
  48. void* mpData;
  49. bool mbCreated;
  50. char mName[32];
  51. T* mpT; // For debug purposes only.
  52. };
  53. template <typename T>
  54. inline Shared<T>::Shared()
  55. : mMapping(NULL)
  56. , mpData(NULL)
  57. , mbCreated(false)
  58. , mpT(NULL)
  59. {
  60. }
  61. template <typename T>
  62. inline Shared<T>::Shared(const char* pName)
  63. : mMapping(NULL)
  64. , mpData(NULL)
  65. , mbCreated(false)
  66. , mpT(NULL)
  67. {
  68. Init(pName);
  69. }
  70. template <typename T>
  71. inline Shared<T>::~Shared()
  72. {
  73. Shutdown();
  74. }
  75. template <typename T>
  76. inline bool Shared<T>::Init(const char* pName)
  77. {
  78. bool bReturnValue = false;
  79. if(pName)
  80. strncpy(mName, pName, sizeof(mName));
  81. else
  82. mName[0] = 0;
  83. mName[sizeof(mName) - 1] = 0;
  84. char mutexName[sizeof(mName) + 16];
  85. strcpy(mutexName, mName);
  86. strcat(mutexName, ".SharedMutex");
  87. HANDLE hMutex = CreateMutexA(NULL, FALSE, mutexName);
  88. EAT_ASSERT(hMutex != NULL);
  89. if(hMutex != NULL)
  90. {
  91. WaitForSingleObject(hMutex, INFINITE); // This lock should always be fast, as it belongs to us and we only hold onto it very temporarily.
  92. const size_t kDataSize = sizeof(T) + 8; // Add bytes so that we can store a ref-count of our own after the mpData.
  93. mMapping = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, kDataSize, mName);
  94. if(mMapping)
  95. {
  96. mbCreated = (GetLastError() != ERROR_ALREADY_EXISTS);
  97. mpData = MapViewOfFile(mMapping, FILE_MAP_ALL_ACCESS, 0, 0, kDataSize);
  98. uint32_t& refCount = GetRefCount(); // The ref count is stored at the end of the mapped data.
  99. if(mbCreated) // If we were the first one to create this, then construct it.
  100. {
  101. new(mpData) T;
  102. refCount = 1;
  103. }
  104. else
  105. refCount++;
  106. mpT = static_cast<T*>(mpData); // For debug purposes only.
  107. bReturnValue = true;
  108. }
  109. ReleaseMutex(hMutex);
  110. CloseHandle(hMutex);
  111. }
  112. return bReturnValue;
  113. }
  114. template <typename T>
  115. inline void Shared<T>::Shutdown()
  116. {
  117. char mutexName[sizeof(mName) + 16];
  118. strcpy(mutexName, mName);
  119. strcat(mutexName, ".SharedMutex");
  120. HANDLE hMutex = CreateMutexA(NULL, FALSE, mutexName);
  121. EAT_ASSERT(hMutex != NULL);
  122. if(hMutex != NULL)
  123. {
  124. WaitForSingleObject(hMutex, INFINITE); // This lock should always be fast, as it belongs to us and we only hold onto it very temporarily.
  125. if(mMapping)
  126. {
  127. if(mpData)
  128. {
  129. uint32_t& refCount = GetRefCount(); // The ref count is stored at the end of the mapped data.
  130. if(refCount == 1) // If we are the last to use it,
  131. static_cast<T*>(mpData)->~T();
  132. else
  133. refCount--;
  134. UnmapViewOfFile(mpData);
  135. mpData = NULL;
  136. }
  137. CloseHandle(mMapping);
  138. mMapping = 0;
  139. }
  140. ReleaseMutex(hMutex);
  141. CloseHandle(hMutex);
  142. }
  143. }
  144. template <typename T>
  145. inline uint32_t& Shared<T>::GetRefCount()
  146. {
  147. // There will be space after T because we allocated it in Init.
  148. uint32_t* pData32 = (uint32_t*)(((uintptr_t)mpData + sizeof(T) + 3) & ~3); // Round up to next 32 bit boundary.
  149. return *pData32;
  150. }
  151. #else
  152. template<typename T>
  153. class Shared
  154. {
  155. public:
  156. Shared() { }
  157. Shared(const char*) { }
  158. bool Init(const char*) { return true; }
  159. void Shutdown() { }
  160. bool IsNew() const { return true; }
  161. T* operator->() { return &mT; }
  162. T mT;
  163. };
  164. #endif // #if defined(EA_PLATFORM_WINDOWS)
  165. } // namespace Thread
  166. } // namespace EA
  167. namespace EA
  168. {
  169. namespace Thread
  170. {
  171. /////////////////////////////////////////////////////////////////////////
  172. /// EARWMutexIPData
  173. ///
  174. #if EA_WINAPI_FAMILY_PARTITION(EA_WINAPI_PARTITION_DESKTOP)
  175. struct EATHREADLIB_API SharedData
  176. {
  177. int mnReadWaiters;
  178. int mnWriteWaiters;
  179. int mnReaders;
  180. DWORD mThreadIdWriter; // Need to use a thread id instead of a thread handle.
  181. SharedData() : mnReadWaiters(0), mnWriteWaiters(0), mnReaders(0), mThreadIdWriter(EA::Thread::kSysThreadIdInvalid) { }
  182. };
  183. struct EATHREADLIB_API EARWMutexIPData
  184. {
  185. Shared<SharedData> mSharedData;
  186. HANDLE mMutex;
  187. HANDLE mReadSemaphore;
  188. HANDLE mWriteSemaphore;
  189. EARWMutexIPData();
  190. ~EARWMutexIPData();
  191. bool Init(const char* pName);
  192. void Shutdown();
  193. private:
  194. EARWMutexIPData(const EARWMutexIPData&);
  195. EARWMutexIPData& operator=(const EARWMutexIPData&);
  196. };
  197. #else
  198. struct EATHREADLIB_API EARWMutexIPData
  199. {
  200. EARWMutexIPData(){}
  201. private:
  202. EARWMutexIPData(const EARWMutexIPData&);
  203. EARWMutexIPData& operator=(const EARWMutexIPData&);
  204. };
  205. #endif
  206. /// RWMutexParameters
  207. struct EATHREADLIB_API RWMutexIPParameters
  208. {
  209. bool mbIntraProcess; /// True if the mutex is intra-process, else inter-process.
  210. char mName[16]; /// Mutex name, applicable only to platforms that recognize named synchronization objects.
  211. RWMutexIPParameters(bool bIntraProcess = true, const char* pName = NULL);
  212. };
  213. /// class RWMutexIP
  214. /// Implements an interprocess multiple reader / single writer mutex.
  215. /// This allows for significantly higher performance when mpData to be protected
  216. /// is read much more frequently than written. In this case, a waiting writer
  217. /// gets top priority and all new readers block after a waiter starts waiting.
  218. class EATHREADLIB_API RWMutexIP
  219. {
  220. public:
  221. enum Result
  222. {
  223. kResultError = -1,
  224. kResultTimeout = -2
  225. };
  226. enum LockType
  227. {
  228. kLockTypeNone = 0,
  229. kLockTypeRead = 1,
  230. kLockTypeWrite = 2
  231. };
  232. /// RWMutexIP
  233. /// For immediate default initialization, use no args.
  234. /// For custom immediate initialization, supply a first argument.
  235. /// For deferred initialization, use RWMutexIP(NULL, false) then later call Init.
  236. /// For deferred initialization of an array of objects, create an empty
  237. /// subclass whose default constructor chains back to RWMutexIP(NULL, false).
  238. RWMutexIP(const RWMutexIPParameters* pRWMutexIPParameters = NULL, bool bDefaultParameters = true);
  239. /// ~RWMutexIP
  240. /// Destroys an existing mutex. The mutex must not be locked by any thread,
  241. /// otherwise the resulting behaviour is undefined.
  242. ~RWMutexIP();
  243. /// Init
  244. /// Initializes the mutex if not done so in the constructor.
  245. /// This should only be called in the case that this class was constructed
  246. /// with RWMutexIP(NULL, false).
  247. bool Init(const RWMutexIPParameters* pRWMutexIPParameters);
  248. /// Lock
  249. /// Returns the new lock count for the given lock type.
  250. ///
  251. /// Note that the timeout is specified in absolute time and not relative time.
  252. ///
  253. /// Note also that due to the way thread scheduling works -- particularly in a
  254. /// time-sliced threading environment -- that the timeout value is a hint and
  255. /// the actual amount of time passed before the timeout occurs may be significantly
  256. /// more or less than the specified timeout time.
  257. ///
  258. int Lock(LockType lockType, const ThreadTime& timeoutAbsolute = EA::Thread::kTimeoutNone);
  259. /// Unlock
  260. /// Unlocks the mutex. The mutex must already be locked by the
  261. /// calling thread. Otherwise the behaviour is not defined.
  262. /// Return value is the lock count value immediately upon unlock
  263. /// or is one of enum Result.
  264. int Unlock();
  265. /// GetLockCount
  266. int GetLockCount(LockType lockType);
  267. /// GetPlatformData
  268. /// Returns the platform-specific mpData handle for debugging uses or
  269. /// other cases whereby special (and non-portable) uses are required.
  270. void* GetPlatformData()
  271. { return &mRWMutexIPData; }
  272. protected:
  273. EARWMutexIPData mRWMutexIPData;
  274. private:
  275. // Objects of this class are not copyable.
  276. RWMutexIP(const RWMutexIP&){}
  277. RWMutexIP& operator=(const RWMutexIP&){ return *this; }
  278. };
  279. /// RWMutexIPFactory
  280. ///
  281. /// Implements a factory-based creation and destruction mechanism for class RWMutexIP.
  282. /// A primary use of this would be to allow the RWMutexIP implementation to reside in
  283. /// a private library while users of the class interact only with the interface
  284. /// header and the factory. The factory provides conventional create/destroy
  285. /// semantics which use global operator new, but also provides manual construction/
  286. /// destruction semantics so that the user can provide for memory allocation
  287. /// and deallocation.
  288. class EATHREADLIB_API RWMutexIPFactory
  289. {
  290. public:
  291. static RWMutexIP* CreateRWMutexIP(); // Internally implemented as: return new RWMutexIP;
  292. static void DestroyRWMutexIP(RWMutexIP* pRWMutex); // Internally implemented as: delete pRWMutex;
  293. static size_t GetRWMutexIPSize(); // Internally implemented as: return sizeof(RWMutexIP);
  294. static RWMutexIP* ConstructRWMutexIP(void* pMemory); // Internally implemented as: return new(pMemory) RWMutexIP;
  295. static void DestructRWMutexIP(RWMutexIP* pRWMutex); // Internally implemented as: pRWMutex->~RWMutexIP();
  296. };
  297. } // namespace Thread
  298. } // namespace EA
  299. namespace EA
  300. {
  301. namespace Thread
  302. {
  303. /// class AutoRWMutexIP
  304. /// An AutoRWMutex locks the RWMutexIP in its constructor and
  305. /// unlocks the AutoRWMutex in its destructor (when it goes out of scope).
  306. class AutoRWMutexIP
  307. {
  308. public:
  309. AutoRWMutexIP(RWMutexIP& mutex, RWMutexIP::LockType lockType)
  310. : mMutex(mutex)
  311. { mMutex.Lock(lockType); }
  312. ~AutoRWMutexIP()
  313. { mMutex.Unlock(); }
  314. protected:
  315. RWMutexIP& mMutex;
  316. // Prevent copying by default, as copying is dangerous.
  317. AutoRWMutexIP(const AutoRWMutexIP&);
  318. const AutoRWMutexIP& operator=(const AutoRWMutexIP&);
  319. };
  320. } // namespace Thread
  321. } // namespace EA
  322. EA_RESTORE_VC_WARNING()
  323. #endif // EATHREAD_EATHREAD_RWMUTEX_IP_H