lifetime_test.cc 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <cstdlib>
  15. #include <thread> // NOLINT(build/c++11), Abseil test
  16. #include <type_traits>
  17. #include "absl/base/attributes.h"
  18. #include "absl/base/const_init.h"
  19. #include "absl/base/internal/raw_logging.h"
  20. #include "absl/base/thread_annotations.h"
  21. #include "absl/synchronization/mutex.h"
  22. #include "absl/synchronization/notification.h"
  23. namespace {
  24. // A two-threaded test which checks that Mutex, CondVar, and Notification have
  25. // correct basic functionality. The intent is to establish that they
  26. // function correctly in various phases of construction and destruction.
  27. //
  28. // Thread one acquires a lock on 'mutex', wakes thread two via 'notification',
  29. // then waits for 'state' to be set, as signalled by 'condvar'.
  30. //
  31. // Thread two waits on 'notification', then sets 'state' inside the 'mutex',
  32. // signalling the change via 'condvar'.
  33. //
  34. // These tests use ABSL_RAW_CHECK to validate invariants, rather than EXPECT or
  35. // ASSERT from gUnit, because we need to invoke them during global destructors,
  36. // when gUnit teardown would have already begun.
  37. void ThreadOne(absl::Mutex* mutex, absl::CondVar* condvar,
  38. absl::Notification* notification, bool* state) {
  39. // Test that the notification is in a valid initial state.
  40. ABSL_RAW_CHECK(!notification->HasBeenNotified(), "invalid Notification");
  41. ABSL_RAW_CHECK(*state == false, "*state not initialized");
  42. {
  43. absl::MutexLock lock(mutex);
  44. notification->Notify();
  45. ABSL_RAW_CHECK(notification->HasBeenNotified(), "invalid Notification");
  46. while (*state == false) {
  47. condvar->Wait(mutex);
  48. }
  49. }
  50. }
  51. void ThreadTwo(absl::Mutex* mutex, absl::CondVar* condvar,
  52. absl::Notification* notification, bool* state) {
  53. ABSL_RAW_CHECK(*state == false, "*state not initialized");
  54. // Wake thread one
  55. notification->WaitForNotification();
  56. ABSL_RAW_CHECK(notification->HasBeenNotified(), "invalid Notification");
  57. {
  58. absl::MutexLock lock(mutex);
  59. *state = true;
  60. condvar->Signal();
  61. }
  62. }
  63. // Launch thread 1 and thread 2, and block on their completion.
  64. // If any of 'mutex', 'condvar', or 'notification' is nullptr, use a locally
  65. // constructed instance instead.
  66. void RunTests(absl::Mutex* mutex, absl::CondVar* condvar) {
  67. absl::Mutex default_mutex;
  68. absl::CondVar default_condvar;
  69. absl::Notification notification;
  70. if (!mutex) {
  71. mutex = &default_mutex;
  72. }
  73. if (!condvar) {
  74. condvar = &default_condvar;
  75. }
  76. bool state = false;
  77. std::thread thread_one(ThreadOne, mutex, condvar, &notification, &state);
  78. std::thread thread_two(ThreadTwo, mutex, condvar, &notification, &state);
  79. thread_one.join();
  80. thread_two.join();
  81. }
  82. void TestLocals() {
  83. absl::Mutex mutex;
  84. absl::CondVar condvar;
  85. RunTests(&mutex, &condvar);
  86. }
  87. // Normal kConstInit usage
  88. ABSL_CONST_INIT absl::Mutex const_init_mutex(absl::kConstInit);
  89. void TestConstInitGlobal() { RunTests(&const_init_mutex, nullptr); }
  90. // Global variables during start and termination
  91. //
  92. // In a translation unit, static storage duration variables are initialized in
  93. // the order of their definitions, and destroyed in the reverse order of their
  94. // definitions. We can use this to arrange for tests to be run on these objects
  95. // before they are created, and after they are destroyed.
  96. using Function = void (*)();
  97. class OnConstruction {
  98. public:
  99. explicit OnConstruction(Function fn) { fn(); }
  100. };
  101. class OnDestruction {
  102. public:
  103. explicit OnDestruction(Function fn) : fn_(fn) {}
  104. ~OnDestruction() { fn_(); }
  105. private:
  106. Function fn_;
  107. };
  108. // These tests require that the compiler correctly supports C++11 constant
  109. // initialization... but MSVC has a known regression since v19.10:
  110. // https://developercommunity.visualstudio.com/content/problem/336946/class-with-constexpr-constructor-not-using-static.html
  111. // TODO(epastor): Limit the affected range once MSVC fixes this bug.
  112. #if defined(__clang__) || !(defined(_MSC_VER) && _MSC_VER > 1900)
  113. // kConstInit
  114. // Test early usage. (Declaration comes first; definitions must appear after
  115. // the test runner.)
  116. extern absl::Mutex early_const_init_mutex;
  117. // (Normally I'd write this +[], to make the cast-to-function-pointer explicit,
  118. // but in some MSVC setups we support, lambdas provide conversion operators to
  119. // different flavors of function pointers, making this trick ambiguous.)
  120. OnConstruction test_early_const_init([] {
  121. RunTests(&early_const_init_mutex, nullptr);
  122. });
  123. // This definition appears before test_early_const_init, but it should be
  124. // initialized first (due to constant initialization). Test that the object
  125. // actually works when constructed this way.
  126. ABSL_CONST_INIT absl::Mutex early_const_init_mutex(absl::kConstInit);
  127. // Furthermore, test that the const-init c'tor doesn't stomp over the state of
  128. // a Mutex. Really, this is a test that the platform under test correctly
  129. // supports C++11 constant initialization. (The constant-initialization
  130. // constructors of globals "happen at link time"; memory is pre-initialized,
  131. // before the constructors of either grab_lock or check_still_locked are run.)
  132. extern absl::Mutex const_init_sanity_mutex;
  133. OnConstruction grab_lock([]() ABSL_NO_THREAD_SAFETY_ANALYSIS {
  134. const_init_sanity_mutex.Lock();
  135. });
  136. ABSL_CONST_INIT absl::Mutex const_init_sanity_mutex(absl::kConstInit);
  137. OnConstruction check_still_locked([]() ABSL_NO_THREAD_SAFETY_ANALYSIS {
  138. const_init_sanity_mutex.AssertHeld();
  139. const_init_sanity_mutex.Unlock();
  140. });
  141. #endif // defined(__clang__) || !(defined(_MSC_VER) && _MSC_VER > 1900)
  142. // Test shutdown usage. (Declarations come first; definitions must appear after
  143. // the test runner.)
  144. extern absl::Mutex late_const_init_mutex;
  145. // OnDestruction is being used here as a global variable, even though it has a
  146. // non-trivial destructor. This is against the style guide. We're violating
  147. // that rule here to check that the exception we allow for kConstInit is safe.
  148. // NOLINTNEXTLINE
  149. OnDestruction test_late_const_init([] {
  150. RunTests(&late_const_init_mutex, nullptr);
  151. });
  152. ABSL_CONST_INIT absl::Mutex late_const_init_mutex(absl::kConstInit);
  153. } // namespace
  154. int main() {
  155. TestLocals();
  156. TestConstInitGlobal();
  157. // Explicitly call exit(0) here, to make it clear that we intend for the
  158. // above global object destructors to run.
  159. std::exit(0);
  160. }