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