mutex.h 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. namespace protobuf {
  60. namespace internal {
  61. #define GOOGLE_PROTOBUF_LINKER_INITIALIZED
  62. #ifdef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP
  63. // This class is a lightweight replacement for std::mutex on Windows platforms.
  64. // std::mutex does not work on Windows XP SP2 with the latest VC++ libraries,
  65. // because it utilizes the Concurrency Runtime that is only supported on Windows
  66. // XP SP3 and above.
  67. class PROTOBUF_EXPORT CriticalSectionLock {
  68. public:
  69. CriticalSectionLock() { InitializeCriticalSection(&critical_section_); }
  70. ~CriticalSectionLock() { DeleteCriticalSection(&critical_section_); }
  71. void lock() { EnterCriticalSection(&critical_section_); }
  72. void unlock() { LeaveCriticalSection(&critical_section_); }
  73. private:
  74. CRITICAL_SECTION critical_section_;
  75. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CriticalSectionLock);
  76. };
  77. #endif
  78. // In MSVC std::mutex does not have a constexpr constructor.
  79. // This wrapper makes the constructor constexpr.
  80. template <typename T>
  81. class CallOnceInitializedMutex {
  82. public:
  83. constexpr CallOnceInitializedMutex() : flag_{}, buf_{} {}
  84. ~CallOnceInitializedMutex() { get().~T(); }
  85. void lock() { get().lock(); }
  86. void unlock() { get().unlock(); }
  87. private:
  88. T& get() {
  89. std::call_once(flag_, [&] { ::new (static_cast<void*>(&buf_)) T(); });
  90. return reinterpret_cast<T&>(buf_);
  91. }
  92. std::once_flag flag_;
  93. alignas(T) char buf_[sizeof(T)];
  94. };
  95. // Mutex is a natural type to wrap. As both google and other organization have
  96. // specialized mutexes. gRPC also provides an injection mechanism for custom
  97. // mutexes.
  98. class GOOGLE_PROTOBUF_CAPABILITY("mutex") PROTOBUF_EXPORT WrappedMutex {
  99. public:
  100. #if defined(__QNX__)
  101. constexpr WrappedMutex() = default;
  102. #else
  103. constexpr WrappedMutex() {}
  104. #endif
  105. void Lock() GOOGLE_PROTOBUF_ACQUIRE() { mu_.lock(); }
  106. void Unlock() GOOGLE_PROTOBUF_RELEASE() { mu_.unlock(); }
  107. // Crash if this Mutex is not held exclusively by this thread.
  108. // May fail to crash when it should; will never crash when it should not.
  109. void AssertHeld() const {}
  110. private:
  111. #if defined(GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP)
  112. CallOnceInitializedMutex<CriticalSectionLock> mu_{};
  113. #elif defined(_WIN32)
  114. CallOnceInitializedMutex<std::mutex> mu_{};
  115. #else
  116. std::mutex mu_{};
  117. #endif
  118. };
  119. using Mutex = WrappedMutex;
  120. // MutexLock(mu) acquires mu when constructed and releases it when destroyed.
  121. class GOOGLE_PROTOBUF_SCOPED_CAPABILITY PROTOBUF_EXPORT MutexLock {
  122. public:
  123. explicit MutexLock(Mutex *mu) GOOGLE_PROTOBUF_ACQUIRE(mu) : mu_(mu) {
  124. this->mu_->Lock();
  125. }
  126. ~MutexLock() GOOGLE_PROTOBUF_RELEASE() { this->mu_->Unlock(); }
  127. private:
  128. Mutex *const mu_;
  129. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock);
  130. };
  131. // TODO(kenton): Implement these? Hard to implement portably.
  132. typedef MutexLock ReaderMutexLock;
  133. typedef MutexLock WriterMutexLock;
  134. // MutexLockMaybe is like MutexLock, but is a no-op when mu is nullptr.
  135. class PROTOBUF_EXPORT MutexLockMaybe {
  136. public:
  137. explicit MutexLockMaybe(Mutex *mu) :
  138. mu_(mu) { if (this->mu_ != nullptr) { this->mu_->Lock(); } }
  139. ~MutexLockMaybe() { if (this->mu_ != nullptr) { this->mu_->Unlock(); } }
  140. private:
  141. Mutex *const mu_;
  142. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe);
  143. };
  144. #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
  145. template<typename T>
  146. class ThreadLocalStorage {
  147. public:
  148. ThreadLocalStorage() {
  149. pthread_key_create(&key_, &ThreadLocalStorage::Delete);
  150. }
  151. ~ThreadLocalStorage() {
  152. pthread_key_delete(key_);
  153. }
  154. T* Get() {
  155. T* result = static_cast<T*>(pthread_getspecific(key_));
  156. if (result == nullptr) {
  157. result = new T();
  158. pthread_setspecific(key_, result);
  159. }
  160. return result;
  161. }
  162. private:
  163. static void Delete(void* value) {
  164. delete static_cast<T*>(value);
  165. }
  166. pthread_key_t key_;
  167. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ThreadLocalStorage);
  168. };
  169. #endif
  170. } // namespace internal
  171. // We made these internal so that they would show up as such in the docs,
  172. // but we don't want to stick "internal::" in front of them everywhere.
  173. using internal::Mutex;
  174. using internal::MutexLock;
  175. using internal::ReaderMutexLock;
  176. using internal::WriterMutexLock;
  177. using internal::MutexLockMaybe;
  178. } // namespace protobuf
  179. } // namespace google
  180. #undef GOOGLE_PROTOBUF_ACQUIRE
  181. #undef GOOGLE_PROTOBUF_RELEASE
  182. #include <google/protobuf/port_undef.inc>
  183. #endif // GOOGLE_PROTOBUF_STUBS_MUTEX_H_