You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

mutex.h 9.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. // Copyright (c) 2006, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. #ifndef GOOGLE_PROTOBUF_STUBS_MUTEX_H_
  30. #define GOOGLE_PROTOBUF_STUBS_MUTEX_H_
  31. #include <mutex>
  32. #ifdef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP
  33. #include <windows.h>
  34. // GetMessage conflicts with GeneratedMessageReflection::GetMessage().
  35. #ifdef GetMessage
  36. #undef GetMessage
  37. #endif
  38. #endif
  39. #include <google/protobuf/stubs/macros.h>
  40. // Define thread-safety annotations for use below, if we are building with
  41. // Clang.
  42. #if defined(__clang__) && !defined(SWIG)
  43. #define GOOGLE_PROTOBUF_ACQUIRE(...) \
  44. __attribute__((acquire_capability(__VA_ARGS__)))
  45. #define GOOGLE_PROTOBUF_RELEASE(...) \
  46. __attribute__((release_capability(__VA_ARGS__)))
  47. #define GOOGLE_PROTOBUF_SCOPED_CAPABILITY __attribute__((scoped_lockable))
  48. #define GOOGLE_PROTOBUF_CAPABILITY(x) __attribute__((capability(x)))
  49. #else
  50. #define GOOGLE_PROTOBUF_ACQUIRE(...)
  51. #define GOOGLE_PROTOBUF_RELEASE(...)
  52. #define GOOGLE_PROTOBUF_SCOPED_CAPABILITY
  53. #define GOOGLE_PROTOBUF_CAPABILITY(x)
  54. #endif
  55. #include <google/protobuf/port_def.inc>
  56. // ===================================================================
  57. // emulates google3/base/mutex.h
  58. namespace google
  59. {
  60. namespace protobuf
  61. {
  62. namespace internal
  63. {
  64. #define GOOGLE_PROTOBUF_LINKER_INITIALIZED
  65. #ifdef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP
  66. // This class is a lightweight replacement for std::mutex on Windows platforms.
  67. // std::mutex does not work on Windows XP SP2 with the latest VC++ libraries,
  68. // because it utilizes the Concurrency Runtime that is only supported on Windows
  69. // XP SP3 and above.
  70. class PROTOBUF_EXPORT CriticalSectionLock
  71. {
  72. public:
  73. CriticalSectionLock()
  74. {
  75. InitializeCriticalSection(&critical_section_);
  76. }
  77. ~CriticalSectionLock()
  78. {
  79. DeleteCriticalSection(&critical_section_);
  80. }
  81. void lock()
  82. {
  83. EnterCriticalSection(&critical_section_);
  84. }
  85. void unlock()
  86. {
  87. LeaveCriticalSection(&critical_section_);
  88. }
  89. private:
  90. CRITICAL_SECTION critical_section_;
  91. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CriticalSectionLock);
  92. };
  93. #endif
  94. // In MSVC std::mutex does not have a constexpr constructor.
  95. // This wrapper makes the constructor constexpr.
  96. template<typename T>
  97. class CallOnceInitializedMutex
  98. {
  99. public:
  100. constexpr CallOnceInitializedMutex() :
  101. flag_{},
  102. buf_{}
  103. {
  104. }
  105. ~CallOnceInitializedMutex()
  106. {
  107. get().~T();
  108. }
  109. void lock()
  110. {
  111. get().lock();
  112. }
  113. void unlock()
  114. {
  115. get().unlock();
  116. }
  117. private:
  118. T& get()
  119. {
  120. std::call_once(flag_, [&]
  121. { ::new (static_cast<void*>(&buf_)) T(); });
  122. return reinterpret_cast<T&>(buf_);
  123. }
  124. std::once_flag flag_;
  125. alignas(T) char buf_[sizeof(T)];
  126. };
  127. // Mutex is a natural type to wrap. As both google and other organization have
  128. // specialized mutexes. gRPC also provides an injection mechanism for custom
  129. // mutexes.
  130. class GOOGLE_PROTOBUF_CAPABILITY("mutex") PROTOBUF_EXPORT WrappedMutex
  131. {
  132. public:
  133. #if defined(__QNX__)
  134. constexpr WrappedMutex() = default;
  135. #else
  136. constexpr WrappedMutex()
  137. {
  138. }
  139. #endif
  140. void Lock() GOOGLE_PROTOBUF_ACQUIRE()
  141. {
  142. mu_.lock();
  143. }
  144. void Unlock() GOOGLE_PROTOBUF_RELEASE()
  145. {
  146. mu_.unlock();
  147. }
  148. // Crash if this Mutex is not held exclusively by this thread.
  149. // May fail to crash when it should; will never crash when it should not.
  150. void AssertHeld() const
  151. {
  152. }
  153. private:
  154. #if defined(GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP)
  155. CallOnceInitializedMutex<CriticalSectionLock> mu_{};
  156. #elif defined(_WIN32)
  157. CallOnceInitializedMutex<std::mutex> mu_{};
  158. #else
  159. std::mutex mu_{};
  160. #endif
  161. };
  162. using Mutex = WrappedMutex;
  163. // MutexLock(mu) acquires mu when constructed and releases it when destroyed.
  164. class GOOGLE_PROTOBUF_SCOPED_CAPABILITY PROTOBUF_EXPORT MutexLock
  165. {
  166. public:
  167. explicit MutexLock(Mutex* mu) GOOGLE_PROTOBUF_ACQUIRE(mu) :
  168. mu_(mu)
  169. {
  170. this->mu_->Lock();
  171. }
  172. ~MutexLock() GOOGLE_PROTOBUF_RELEASE()
  173. {
  174. this->mu_->Unlock();
  175. }
  176. private:
  177. Mutex* const mu_;
  178. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock);
  179. };
  180. // TODO(kenton): Implement these? Hard to implement portably.
  181. typedef MutexLock ReaderMutexLock;
  182. typedef MutexLock WriterMutexLock;
  183. // MutexLockMaybe is like MutexLock, but is a no-op when mu is nullptr.
  184. class PROTOBUF_EXPORT MutexLockMaybe
  185. {
  186. public:
  187. explicit MutexLockMaybe(Mutex* mu) :
  188. mu_(mu)
  189. {
  190. if (this->mu_ != nullptr)
  191. {
  192. this->mu_->Lock();
  193. }
  194. }
  195. ~MutexLockMaybe()
  196. {
  197. if (this->mu_ != nullptr)
  198. {
  199. this->mu_->Unlock();
  200. }
  201. }
  202. private:
  203. Mutex* const mu_;
  204. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe);
  205. };
  206. #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
  207. template<typename T>
  208. class ThreadLocalStorage
  209. {
  210. public:
  211. ThreadLocalStorage()
  212. {
  213. pthread_key_create(&key_, &ThreadLocalStorage::Delete);
  214. }
  215. ~ThreadLocalStorage()
  216. {
  217. pthread_key_delete(key_);
  218. }
  219. T* Get()
  220. {
  221. T* result = static_cast<T*>(pthread_getspecific(key_));
  222. if (result == nullptr)
  223. {
  224. result = new T();
  225. pthread_setspecific(key_, result);
  226. }
  227. return result;
  228. }
  229. private:
  230. static void Delete(void* value)
  231. {
  232. delete static_cast<T*>(value);
  233. }
  234. pthread_key_t key_;
  235. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ThreadLocalStorage);
  236. };
  237. #endif
  238. } // namespace internal
  239. // We made these internal so that they would show up as such in the docs,
  240. // but we don't want to stick "internal::" in front of them everywhere.
  241. using internal::Mutex;
  242. using internal::MutexLock;
  243. using internal::MutexLockMaybe;
  244. using internal::ReaderMutexLock;
  245. using internal::WriterMutexLock;
  246. } // namespace protobuf
  247. } // namespace google
  248. #undef GOOGLE_PROTOBUF_ACQUIRE
  249. #undef GOOGLE_PROTOBUF_RELEASE
  250. #include <google/protobuf/port_undef.inc>
  251. #endif // GOOGLE_PROTOBUF_STUBS_MUTEX_H_