2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <gtest/gtest.h>
21 #include <folly/Foreach.h>
22 #include <folly/Random.h>
23 #include <folly/Synchronized.h>
24 #include <glog/logging.h>
26 #include <condition_variable>
34 namespace sync_tests {
36 inline std::mt19937& getRNG() {
37 static const auto seed = folly::randomNumberSeed();
38 static std::mt19937 rng(seed);
42 void randomSleep(std::chrono::milliseconds min, std::chrono::milliseconds max) {
43 std::uniform_int_distribution<> range(min.count(), max.count());
44 std::chrono::milliseconds duration(range(getRNG()));
45 std::this_thread::sleep_for(duration);
49 * Run a functon simultaneously in a number of different threads.
51 * The function will be passed the index number of the thread it is running in.
52 * This function makes an attempt to synchronize the start of the threads as
53 * best as possible. It waits for all threads to be allocated and started
54 * before invoking the function.
56 template <class Function>
57 void runParallel(size_t numThreads, const Function& function) {
58 std::vector<std::thread> threads;
59 threads.reserve(numThreads);
61 // Variables used to synchronize all threads to try and start them
62 // as close to the same time as possible
64 // TODO: At the moment Synchronized doesn't work with condition variables.
65 // Update this to use Synchronized once the condition_variable support lands.
66 std::mutex threadsReadyMutex;
67 size_t threadsReady = 0;
68 std::condition_variable readyCV;
71 std::condition_variable goCV;
73 auto worker = [&](size_t threadIndex) {
74 // Signal that we are ready
76 std::lock_guard<std::mutex> lock(threadsReadyMutex);
81 // Wait until we are given the signal to start
82 // The purpose of this is to try and make sure all threads start
83 // as close to the same time as possible.
85 std::unique_lock<std::mutex> lock(goMutex);
86 goCV.wait(lock, [&] { return go; });
89 function(threadIndex);
92 // Start all of the threads
93 for (size_t threadIndex = 0; threadIndex < numThreads; ++threadIndex) {
94 threads.emplace_back([threadIndex, &worker]() { worker(threadIndex); });
97 // Wait for all threads to become ready
99 std::unique_lock<std::mutex> lock(threadsReadyMutex);
100 readyCV.wait(lock, [&] { return threadsReady == numThreads; });
103 std::lock_guard<std::mutex> lock(goMutex);
106 // Now signal the threads that they can go
109 // Wait for all threads to finish
110 for (auto& thread : threads) {
115 template <class Mutex>
117 folly::Synchronized<std::vector<int>, Mutex> obj;
122 EXPECT_EQ(1000, obj2->size());
126 EXPECT_EQ(1001, obj.size());
127 EXPECT_EQ(10, obj.back());
128 EXPECT_EQ(1000, obj2->size());
130 UNSYNCHRONIZED(obj) {
131 EXPECT_EQ(1001, obj->size());
135 SYNCHRONIZED_CONST (obj) {
136 EXPECT_EQ(1001, obj.size());
137 UNSYNCHRONIZED(obj) {
138 EXPECT_EQ(1001, obj->size());
142 SYNCHRONIZED (lockedObj, *&obj) {
143 lockedObj.front() = 2;
146 EXPECT_EQ(1001, obj->size());
147 EXPECT_EQ(10, obj->back());
148 EXPECT_EQ(1000, obj2->size());
150 EXPECT_EQ(FB_ARG_2_OR_1(1, 2), 2);
151 EXPECT_EQ(FB_ARG_2_OR_1(1), 1);
154 template <class Mutex> void testConcurrency() {
155 folly::Synchronized<std::vector<int>, Mutex> v;
156 static const size_t numThreads = 100;
157 // Note: I initially tried using itersPerThread = 1000,
158 // which works fine for most lock types, but std::shared_timed_mutex
159 // appears to be extraordinarily slow. It could take around 30 seconds
160 // to run this test with 1000 iterations per thread using shared_timed_mutex.
161 static const size_t itersPerThread = 100;
163 auto pushNumbers = [&](size_t threadIdx) {
165 for (size_t n = 0; n < itersPerThread; ++n) {
166 v->push_back((itersPerThread * threadIdx) + n);
170 runParallel(numThreads, pushNumbers);
172 std::vector<int> result;
175 EXPECT_EQ(numThreads * itersPerThread, result.size());
176 sort(result.begin(), result.end());
178 for (size_t i = 0; i < itersPerThread * numThreads; ++i) {
179 EXPECT_EQ(i, result[i]);
183 template <class Mutex> void testDualLocking() {
184 folly::Synchronized<std::vector<int>, Mutex> v;
185 folly::Synchronized<std::map<int, int>, Mutex> m;
187 auto dualLockWorker = [&](size_t threadIdx) {
189 SYNCHRONIZED_DUAL(lv, v, lm, m) {
190 lv.push_back(threadIdx);
191 lm[threadIdx] = threadIdx + 1;
194 SYNCHRONIZED_DUAL(lm, m, lv, v) {
195 lv.push_back(threadIdx);
196 lm[threadIdx] = threadIdx + 1;
200 static const size_t numThreads = 100;
201 runParallel(numThreads, dualLockWorker);
203 std::vector<int> result;
206 EXPECT_EQ(numThreads, result.size());
207 sort(result.begin(), result.end());
209 for (size_t i = 0; i < numThreads; ++i) {
210 EXPECT_EQ(i, result[i]);
214 template <class Mutex> void testDualLockingWithConst() {
215 folly::Synchronized<std::vector<int>, Mutex> v;
216 folly::Synchronized<std::map<int, int>, Mutex> m;
218 auto dualLockWorker = [&](size_t threadIdx) {
221 SYNCHRONIZED_DUAL(lv, v, lm, cm) {
223 lv.push_back(threadIdx);
226 SYNCHRONIZED_DUAL(lm, cm, lv, v) {
228 lv.push_back(threadIdx);
232 static const size_t numThreads = 100;
233 runParallel(numThreads, dualLockWorker);
235 std::vector<int> result;
238 EXPECT_EQ(numThreads, result.size());
239 sort(result.begin(), result.end());
241 for (size_t i = 0; i < numThreads; ++i) {
242 EXPECT_EQ(i, result[i]);
246 template <class Mutex> void testTimedSynchronized() {
247 folly::Synchronized<std::vector<int>, Mutex> v;
248 folly::Synchronized<uint64_t, Mutex> numTimeouts;
250 auto worker = [&](size_t threadIdx) {
252 v->push_back(2 * threadIdx);
254 // Aaand test the TIMED_SYNCHRONIZED macro
256 TIMED_SYNCHRONIZED(5, lv, v) {
258 // Sleep for a random time to ensure we trigger timeouts
261 std::chrono::milliseconds(5), std::chrono::milliseconds(15));
262 lv->push_back(2 * threadIdx + 1);
266 SYNCHRONIZED(numTimeouts) {
272 static const size_t numThreads = 100;
273 runParallel(numThreads, worker);
275 std::vector<int> result;
278 EXPECT_EQ(2 * numThreads, result.size());
279 sort(result.begin(), result.end());
281 for (size_t i = 0; i < 2 * numThreads; ++i) {
282 EXPECT_EQ(i, result[i]);
284 // We generally expect a large number of number timeouts here.
285 // I'm not adding a check for it since it's theoretically possible that
286 // we might get 0 timeouts depending on the CPU scheduling if our threads
287 // don't get to run very often.
288 uint64_t finalNumTimeouts = 0;
289 SYNCHRONIZED(numTimeouts) {
290 finalNumTimeouts = numTimeouts;
292 LOG(INFO) << "testTimedSynchronized: " << finalNumTimeouts << " timeouts";
295 template <class Mutex> void testTimedSynchronizedWithConst() {
296 folly::Synchronized<std::vector<int>, Mutex> v;
297 folly::Synchronized<uint64_t, Mutex> numTimeouts;
299 auto worker = [&](size_t threadIdx) {
301 v->push_back(threadIdx);
303 // Test TIMED_SYNCHRONIZED_CONST
305 TIMED_SYNCHRONIZED_CONST(10, lv, v) {
307 // Sleep while holding the lock.
309 // This will block other threads from acquiring the write lock to add
310 // their thread index to v, but it won't block threads that have
311 // entered the for loop and are trying to acquire a read lock.
313 // For lock types that give preference to readers rather than writers,
314 // this will tend to serialize all threads on the wlock() above.
316 std::chrono::milliseconds(5), std::chrono::milliseconds(15));
317 auto found = std::find(lv->begin(), lv->end(), threadIdx);
318 CHECK(found != lv->end());
321 SYNCHRONIZED(numTimeouts) {
329 static const size_t numThreads = 100;
330 runParallel(numThreads, worker);
332 std::vector<int> result;
335 EXPECT_EQ(numThreads, result.size());
336 sort(result.begin(), result.end());
338 for (size_t i = 0; i < numThreads; ++i) {
339 EXPECT_EQ(i, result[i]);
341 // We generally expect a small number of timeouts here.
342 // For locks that give readers preference over writers this should usually
343 // be 0. With locks that give writers preference we do see a small-ish
344 // number of read timeouts.
345 uint64_t finalNumTimeouts = 0;
346 SYNCHRONIZED(numTimeouts) {
347 finalNumTimeouts = numTimeouts;
349 LOG(INFO) << "testTimedSynchronizedWithConst: " << finalNumTimeouts
353 template <class Mutex> void testConstCopy() {
354 std::vector<int> input = {1, 2, 3};
355 const folly::Synchronized<std::vector<int>, Mutex> v(input);
357 std::vector<int> result;
360 EXPECT_EQ(input, result);
363 EXPECT_EQ(input, result);
366 struct NotCopiableNotMovable {
367 NotCopiableNotMovable(int, const char*) {}
368 NotCopiableNotMovable(const NotCopiableNotMovable&) = delete;
369 NotCopiableNotMovable& operator=(const NotCopiableNotMovable&) = delete;
370 NotCopiableNotMovable(NotCopiableNotMovable&&) = delete;
371 NotCopiableNotMovable& operator=(NotCopiableNotMovable&&) = delete;
374 template <class Mutex> void testInPlaceConstruction() {
375 // This won't compile without construct_in_place
376 folly::Synchronized<NotCopiableNotMovable> a(
377 folly::construct_in_place, 5, "a"