mutex.h 6.6 KB

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