add Synchronized::withLock() methods
[folly.git] / folly / test / SynchronizedTestLib-inl.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <gtest/gtest.h>
20
21 #include <folly/Foreach.h>
22 #include <folly/Random.h>
23 #include <folly/Synchronized.h>
24 #include <glog/logging.h>
25 #include <algorithm>
26 #include <condition_variable>
27 #include <functional>
28 #include <map>
29 #include <random>
30 #include <thread>
31 #include <vector>
32
33 namespace folly {
34 namespace sync_tests {
35
36 inline std::mt19937& getRNG() {
37   static const auto seed = folly::randomNumberSeed();
38   static std::mt19937 rng(seed);
39   return rng;
40 }
41
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);
46 }
47
48 /*
49  * Run a functon simultaneously in a number of different threads.
50  *
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.
55  */
56 template <class Function>
57 void runParallel(size_t numThreads, const Function& function) {
58   std::vector<std::thread> threads;
59   threads.reserve(numThreads);
60
61   // Variables used to synchronize all threads to try and start them
62   // as close to the same time as possible
63   folly::Synchronized<size_t, std::mutex> threadsReady(0);
64   std::condition_variable readyCV;
65   folly::Synchronized<bool, std::mutex> go(false);
66   std::condition_variable goCV;
67
68   auto worker = [&](size_t threadIndex) {
69     // Signal that we are ready
70     ++(*threadsReady.lock());
71     readyCV.notify_one();
72
73     // Wait until we are given the signal to start
74     // The purpose of this is to try and make sure all threads start
75     // as close to the same time as possible.
76     {
77       auto lockedGo = go.lock();
78       goCV.wait(lockedGo.getUniqueLock(), [&] { return *lockedGo; });
79     }
80
81     function(threadIndex);
82   };
83
84   // Start all of the threads
85   for (size_t threadIndex = 0; threadIndex < numThreads; ++threadIndex) {
86     threads.emplace_back([threadIndex, &worker]() { worker(threadIndex); });
87   }
88
89   // Wait for all threads to become ready
90   {
91     auto readyLocked = threadsReady.lock();
92     readyCV.wait(readyLocked.getUniqueLock(), [&] {
93       return *readyLocked == numThreads;
94     });
95   }
96   // Now signal the threads that they can go
97   go = true;
98   goCV.notify_all();
99
100   // Wait for all threads to finish
101   for (auto& thread : threads) {
102     thread.join();
103   }
104 }
105
106 // testBasic() version for shared lock types
107 template <class Mutex>
108 typename std::enable_if<folly::LockTraits<Mutex>::is_shared>::type
109 testBasicImpl() {
110   folly::Synchronized<std::vector<int>, Mutex> obj;
111   const auto& constObj = obj;
112
113   obj.wlock()->resize(1000);
114
115   folly::Synchronized<std::vector<int>, Mutex> obj2{*obj.wlock()};
116   EXPECT_EQ(1000, obj2.rlock()->size());
117
118   {
119     auto lockedObj = obj.wlock();
120     lockedObj->push_back(10);
121     EXPECT_EQ(1001, lockedObj->size());
122     EXPECT_EQ(10, lockedObj->back());
123     EXPECT_EQ(1000, obj2.wlock()->size());
124     EXPECT_EQ(1000, obj2.rlock()->size());
125
126     {
127       auto unlocker = lockedObj.scopedUnlock();
128       EXPECT_EQ(1001, obj.wlock()->size());
129     }
130   }
131
132   {
133     auto lockedObj = obj.rlock();
134     EXPECT_EQ(1001, lockedObj->size());
135     EXPECT_EQ(1001, obj.rlock()->size());
136     {
137       auto unlocker = lockedObj.scopedUnlock();
138       EXPECT_EQ(1001, obj.wlock()->size());
139     }
140   }
141
142   obj.wlock()->front() = 2;
143
144   {
145     // contextualLock() on a const reference should grab a shared lock
146     auto lockedObj = constObj.contextualLock();
147     EXPECT_EQ(2, lockedObj->front());
148     EXPECT_EQ(2, constObj.rlock()->front());
149     EXPECT_EQ(2, obj.rlock()->front());
150   }
151
152   EXPECT_EQ(1001, obj.rlock()->size());
153   EXPECT_EQ(2, obj.rlock()->front());
154   EXPECT_EQ(10, obj.rlock()->back());
155   EXPECT_EQ(1000, obj2.rlock()->size());
156 }
157
158 // testBasic() version for non-shared lock types
159 template <class Mutex>
160 typename std::enable_if<!folly::LockTraits<Mutex>::is_shared>::type
161 testBasicImpl() {
162   folly::Synchronized<std::vector<int>, Mutex> obj;
163   const auto& constObj = obj;
164
165   obj.lock()->resize(1000);
166
167   folly::Synchronized<std::vector<int>, Mutex> obj2{*obj.lock()};
168   EXPECT_EQ(1000, obj2.lock()->size());
169
170   {
171     auto lockedObj = obj.lock();
172     lockedObj->push_back(10);
173     EXPECT_EQ(1001, lockedObj->size());
174     EXPECT_EQ(10, lockedObj->back());
175     EXPECT_EQ(1000, obj2.lock()->size());
176
177     {
178       auto unlocker = lockedObj.scopedUnlock();
179       EXPECT_EQ(1001, obj.lock()->size());
180     }
181   }
182   {
183     auto lockedObj = constObj.lock();
184     EXPECT_EQ(1001, lockedObj->size());
185     EXPECT_EQ(10, lockedObj->back());
186     EXPECT_EQ(1000, obj2.lock()->size());
187   }
188
189   obj.lock()->front() = 2;
190
191   EXPECT_EQ(1001, obj.lock()->size());
192   EXPECT_EQ(2, obj.lock()->front());
193   EXPECT_EQ(2, obj.contextualLock()->front());
194   EXPECT_EQ(10, obj.lock()->back());
195   EXPECT_EQ(1000, obj2.lock()->size());
196 }
197
198 template <class Mutex>
199 void testBasic() {
200   testBasicImpl<Mutex>();
201 }
202
203 // testWithLock() version for shared lock types
204 template <class Mutex>
205 typename std::enable_if<folly::LockTraits<Mutex>::is_shared>::type
206 testWithLock() {
207   folly::Synchronized<std::vector<int>, Mutex> obj;
208   const auto& constObj = obj;
209
210   // Test withWLock() and withRLock()
211   obj.withWLock([](std::vector<int>& lockedObj) {
212     lockedObj.resize(1000);
213     lockedObj.push_back(10);
214     lockedObj.push_back(11);
215   });
216   obj.withWLock([](const std::vector<int>& lockedObj) {
217     EXPECT_EQ(1002, lockedObj.size());
218   });
219   constObj.withWLock([](const std::vector<int>& lockedObj) {
220     EXPECT_EQ(1002, lockedObj.size());
221     EXPECT_EQ(11, lockedObj.back());
222   });
223   obj.withRLock([](const std::vector<int>& lockedObj) {
224     EXPECT_EQ(1002, lockedObj.size());
225     EXPECT_EQ(11, lockedObj.back());
226   });
227   constObj.withRLock([](const std::vector<int>& lockedObj) {
228     EXPECT_EQ(1002, lockedObj.size());
229   });
230
231 #if __cpp_generic_lambdas >= 201304
232   obj.withWLock([](auto& lockedObj) { lockedObj.push_back(12); });
233   obj.withWLock(
234       [](const auto& lockedObj) { EXPECT_EQ(1003, lockedObj.size()); });
235   constObj.withWLock([](const auto& lockedObj) {
236     EXPECT_EQ(1003, lockedObj.size());
237     EXPECT_EQ(12, lockedObj.back());
238   });
239   obj.withRLock([](const auto& lockedObj) {
240     EXPECT_EQ(1003, lockedObj.size());
241     EXPECT_EQ(12, lockedObj.back());
242   });
243   constObj.withRLock(
244       [](const auto& lockedObj) { EXPECT_EQ(1003, lockedObj.size()); });
245   obj.withWLock([](auto& lockedObj) { lockedObj.pop_back(); });
246 #endif
247
248   // Test withWLockPtr() and withRLockPtr()
249   using SynchType = folly::Synchronized<std::vector<int>, Mutex>;
250 #if __cpp_generic_lambdas >= 201304
251   obj.withWLockPtr([](auto&& lockedObj) { lockedObj->push_back(13); });
252   obj.withRLockPtr([](auto&& lockedObj) {
253     EXPECT_EQ(1003, lockedObj->size());
254     EXPECT_EQ(13, lockedObj->back());
255   });
256   constObj.withRLockPtr([](auto&& lockedObj) {
257     EXPECT_EQ(1003, lockedObj->size());
258     EXPECT_EQ(13, lockedObj->back());
259   });
260   obj.withWLockPtr([&](auto&& lockedObj) {
261     lockedObj->push_back(14);
262     {
263       auto unlocker = lockedObj.scopedUnlock();
264       obj.wlock()->push_back(15);
265     }
266     EXPECT_EQ(15, lockedObj->back());
267   });
268   constObj.withWLockPtr([](auto&& lockedObj) {
269     EXPECT_EQ(1005, lockedObj->size());
270     EXPECT_EQ(15, lockedObj->back());
271   });
272 #else
273   obj.withWLockPtr([](typename SynchType::LockedPtr&& lockedObj) {
274     lockedObj->push_back(13);
275     lockedObj->push_back(14);
276     lockedObj->push_back(15);
277   });
278 #endif
279
280   obj.withWLockPtr([](typename SynchType::LockedPtr&& lockedObj) {
281     lockedObj->push_back(16);
282     EXPECT_EQ(1006, lockedObj->size());
283   });
284   constObj.withWLockPtr([](typename SynchType::ConstWLockedPtr&& lockedObj) {
285     EXPECT_EQ(1006, lockedObj->size());
286     EXPECT_EQ(16, lockedObj->back());
287   });
288   obj.withRLockPtr([](typename SynchType::ConstLockedPtr&& lockedObj) {
289     EXPECT_EQ(1006, lockedObj->size());
290     EXPECT_EQ(16, lockedObj->back());
291   });
292   constObj.withRLockPtr([](typename SynchType::ConstLockedPtr&& lockedObj) {
293     EXPECT_EQ(1006, lockedObj->size());
294     EXPECT_EQ(16, lockedObj->back());
295   });
296 }
297
298 // testWithLock() version for non-shared lock types
299 template <class Mutex>
300 typename std::enable_if<!folly::LockTraits<Mutex>::is_shared>::type
301 testWithLock() {
302   folly::Synchronized<std::vector<int>, Mutex> obj;
303
304   // Test withLock()
305   obj.withLock([](std::vector<int>& lockedObj) {
306     lockedObj.resize(1000);
307     lockedObj.push_back(10);
308     lockedObj.push_back(11);
309   });
310   obj.withLock([](const std::vector<int>& lockedObj) {
311     EXPECT_EQ(1002, lockedObj.size());
312   });
313
314 #if __cpp_generic_lambdas >= 201304
315   obj.withLock([](auto& lockedObj) { lockedObj.push_back(12); });
316   obj.withLock(
317       [](const auto& lockedObj) { EXPECT_EQ(1003, lockedObj.size()); });
318   obj.withLock([](auto& lockedObj) { lockedObj.pop_back(); });
319 #endif
320
321   // Test withLockPtr()
322   using SynchType = folly::Synchronized<std::vector<int>, Mutex>;
323 #if __cpp_generic_lambdas >= 201304
324   obj.withLockPtr([](auto&& lockedObj) { lockedObj->push_back(13); });
325   obj.withLockPtr([](auto&& lockedObj) {
326     EXPECT_EQ(1003, lockedObj->size());
327     EXPECT_EQ(13, lockedObj->back());
328   });
329   obj.withLockPtr([&](auto&& lockedObj) {
330     lockedObj->push_back(14);
331     {
332       auto unlocker = lockedObj.scopedUnlock();
333       obj.lock()->push_back(15);
334     }
335     EXPECT_EQ(1005, lockedObj->size());
336     EXPECT_EQ(15, lockedObj->back());
337   });
338 #else
339   obj.withLockPtr([](typename SynchType::LockedPtr&& lockedObj) {
340     lockedObj->push_back(13);
341     lockedObj->push_back(14);
342     lockedObj->push_back(15);
343   });
344 #endif
345
346   obj.withLockPtr([](typename SynchType::LockedPtr&& lockedObj) {
347     lockedObj->push_back(16);
348     EXPECT_EQ(1006, lockedObj->size());
349   });
350   const auto& constObj = obj;
351   constObj.withLockPtr([](typename SynchType::ConstLockedPtr&& lockedObj) {
352     EXPECT_EQ(1006, lockedObj->size());
353     EXPECT_EQ(16, lockedObj->back());
354   });
355 }
356
357 // Testing the deprecated SYNCHRONIZED and SYNCHRONIZED_CONST APIs
358 template <class Mutex>
359 void testDeprecated() {
360   folly::Synchronized<std::vector<int>, Mutex> obj;
361
362   obj->resize(1000);
363
364   auto obj2 = obj;
365   EXPECT_EQ(1000, obj2->size());
366
367   SYNCHRONIZED (obj) {
368     obj.push_back(10);
369     EXPECT_EQ(1001, obj.size());
370     EXPECT_EQ(10, obj.back());
371     EXPECT_EQ(1000, obj2->size());
372
373     UNSYNCHRONIZED(obj) {
374       EXPECT_EQ(1001, obj->size());
375     }
376   }
377
378   SYNCHRONIZED_CONST (obj) {
379     EXPECT_EQ(1001, obj.size());
380     UNSYNCHRONIZED(obj) {
381       EXPECT_EQ(1001, obj->size());
382     }
383   }
384
385   SYNCHRONIZED (lockedObj, *&obj) {
386     lockedObj.front() = 2;
387   }
388
389   EXPECT_EQ(1001, obj->size());
390   EXPECT_EQ(10, obj->back());
391   EXPECT_EQ(1000, obj2->size());
392
393   EXPECT_EQ(FB_ARG_2_OR_1(1, 2), 2);
394   EXPECT_EQ(FB_ARG_2_OR_1(1), 1);
395 }
396
397 template <class Mutex> void testConcurrency() {
398   folly::Synchronized<std::vector<int>, Mutex> v;
399   static const size_t numThreads = 100;
400   // Note: I initially tried using itersPerThread = 1000,
401   // which works fine for most lock types, but std::shared_timed_mutex
402   // appears to be extraordinarily slow.  It could take around 30 seconds
403   // to run this test with 1000 iterations per thread using shared_timed_mutex.
404   static const size_t itersPerThread = 100;
405
406   auto pushNumbers = [&](size_t threadIdx) {
407     // Test lock()
408     for (size_t n = 0; n < itersPerThread; ++n) {
409       v.contextualLock()->push_back((itersPerThread * threadIdx) + n);
410       sched_yield();
411     }
412   };
413   runParallel(numThreads, pushNumbers);
414
415   std::vector<int> result;
416   v.swap(result);
417
418   EXPECT_EQ(numThreads * itersPerThread, result.size());
419   sort(result.begin(), result.end());
420
421   for (size_t i = 0; i < itersPerThread * numThreads; ++i) {
422     EXPECT_EQ(i, result[i]);
423   }
424 }
425
426 template <class Mutex>
427 void testAcquireLocked() {
428   folly::Synchronized<std::vector<int>, Mutex> v;
429   folly::Synchronized<std::map<int, int>, Mutex> m;
430
431   auto dualLockWorker = [&](size_t threadIdx) {
432     // Note: this will be less awkward with C++ 17's structured
433     // binding functionality, which will make it easier to use the returned
434     // std::tuple.
435     if (threadIdx & 1) {
436       auto ret = acquireLocked(v, m);
437       std::get<0>(ret)->push_back(threadIdx);
438       (*std::get<1>(ret))[threadIdx] = threadIdx + 1;
439     } else {
440       auto ret = acquireLocked(m, v);
441       std::get<1>(ret)->push_back(threadIdx);
442       (*std::get<0>(ret))[threadIdx] = threadIdx + 1;
443     }
444   };
445   static const size_t numThreads = 100;
446   runParallel(numThreads, dualLockWorker);
447
448   std::vector<int> result;
449   v.swap(result);
450
451   EXPECT_EQ(numThreads, result.size());
452   sort(result.begin(), result.end());
453
454   for (size_t i = 0; i < numThreads; ++i) {
455     EXPECT_EQ(i, result[i]);
456   }
457 }
458
459 template <class Mutex>
460 void testAcquireLockedWithConst() {
461   folly::Synchronized<std::vector<int>, Mutex> v;
462   folly::Synchronized<std::map<int, int>, Mutex> m;
463
464   auto dualLockWorker = [&](size_t threadIdx) {
465     const auto& cm = m;
466     if (threadIdx & 1) {
467       auto ret = acquireLocked(v, cm);
468       (void)std::get<1>(ret)->size();
469       std::get<0>(ret)->push_back(threadIdx);
470     } else {
471       auto ret = acquireLocked(cm, v);
472       (void)std::get<0>(ret)->size();
473       std::get<1>(ret)->push_back(threadIdx);
474     }
475   };
476   static const size_t numThreads = 100;
477   runParallel(numThreads, dualLockWorker);
478
479   std::vector<int> result;
480   v.swap(result);
481
482   EXPECT_EQ(numThreads, result.size());
483   sort(result.begin(), result.end());
484
485   for (size_t i = 0; i < numThreads; ++i) {
486     EXPECT_EQ(i, result[i]);
487   }
488 }
489
490 // Testing the deprecated SYNCHRONIZED_DUAL API
491 template <class Mutex> void testDualLocking() {
492   folly::Synchronized<std::vector<int>, Mutex> v;
493   folly::Synchronized<std::map<int, int>, Mutex> m;
494
495   auto dualLockWorker = [&](size_t threadIdx) {
496     if (threadIdx & 1) {
497       SYNCHRONIZED_DUAL(lv, v, lm, m) {
498         lv.push_back(threadIdx);
499         lm[threadIdx] = threadIdx + 1;
500       }
501     } else {
502       SYNCHRONIZED_DUAL(lm, m, lv, v) {
503         lv.push_back(threadIdx);
504         lm[threadIdx] = threadIdx + 1;
505       }
506     }
507   };
508   static const size_t numThreads = 100;
509   runParallel(numThreads, dualLockWorker);
510
511   std::vector<int> result;
512   v.swap(result);
513
514   EXPECT_EQ(numThreads, result.size());
515   sort(result.begin(), result.end());
516
517   for (size_t i = 0; i < numThreads; ++i) {
518     EXPECT_EQ(i, result[i]);
519   }
520 }
521
522 // Testing the deprecated SYNCHRONIZED_DUAL API
523 template <class Mutex> void testDualLockingWithConst() {
524   folly::Synchronized<std::vector<int>, Mutex> v;
525   folly::Synchronized<std::map<int, int>, Mutex> m;
526
527   auto dualLockWorker = [&](size_t threadIdx) {
528     const auto& cm = m;
529     if (threadIdx & 1) {
530       SYNCHRONIZED_DUAL(lv, v, lm, cm) {
531         (void)lm.size();
532         lv.push_back(threadIdx);
533       }
534     } else {
535       SYNCHRONIZED_DUAL(lm, cm, lv, v) {
536         (void)lm.size();
537         lv.push_back(threadIdx);
538       }
539     }
540   };
541   static const size_t numThreads = 100;
542   runParallel(numThreads, dualLockWorker);
543
544   std::vector<int> result;
545   v.swap(result);
546
547   EXPECT_EQ(numThreads, result.size());
548   sort(result.begin(), result.end());
549
550   for (size_t i = 0; i < numThreads; ++i) {
551     EXPECT_EQ(i, result[i]);
552   }
553 }
554
555 template <class Mutex>
556 void testTimed() {
557   folly::Synchronized<std::vector<int>, Mutex> v;
558   folly::Synchronized<uint64_t, Mutex> numTimeouts;
559
560   auto worker = [&](size_t threadIdx) {
561     // Test directly using operator-> on the lock result
562     v.contextualLock()->push_back(2 * threadIdx);
563
564     // Test using lock with a timeout
565     for (;;) {
566       auto lv = v.contextualLock(std::chrono::milliseconds(5));
567       if (!lv) {
568         ++(*numTimeouts.contextualLock());
569         continue;
570       }
571
572       // Sleep for a random time to ensure we trigger timeouts
573       // in other threads
574       randomSleep(std::chrono::milliseconds(5), std::chrono::milliseconds(15));
575       lv->push_back(2 * threadIdx + 1);
576       break;
577     }
578   };
579
580   static const size_t numThreads = 100;
581   runParallel(numThreads, worker);
582
583   std::vector<int> result;
584   v.swap(result);
585
586   EXPECT_EQ(2 * numThreads, result.size());
587   sort(result.begin(), result.end());
588
589   for (size_t i = 0; i < 2 * numThreads; ++i) {
590     EXPECT_EQ(i, result[i]);
591   }
592   // We generally expect a large number of number timeouts here.
593   // I'm not adding a check for it since it's theoretically possible that
594   // we might get 0 timeouts depending on the CPU scheduling if our threads
595   // don't get to run very often.
596   LOG(INFO) << "testTimed: " << *numTimeouts.contextualRLock() << " timeouts";
597
598   // Make sure we can lock with various timeout duration units
599   {
600     auto lv = v.contextualLock(std::chrono::milliseconds(5));
601     EXPECT_TRUE(lv);
602     EXPECT_FALSE(lv.isNull());
603     auto lv2 = v.contextualLock(std::chrono::microseconds(5));
604     // We may or may not acquire lv2 successfully, depending on whether
605     // or not this is a recursive mutex type.
606   }
607   {
608     auto lv = v.contextualLock(std::chrono::seconds(1));
609     EXPECT_TRUE(lv);
610   }
611 }
612
613 template <class Mutex>
614 void testTimedShared() {
615   folly::Synchronized<std::vector<int>, Mutex> v;
616   folly::Synchronized<uint64_t, Mutex> numTimeouts;
617
618   auto worker = [&](size_t threadIdx) {
619     // Test directly using operator-> on the lock result
620     v.wlock()->push_back(threadIdx);
621
622     // Test lock() with a timeout
623     for (;;) {
624       auto lv = v.rlock(std::chrono::milliseconds(10));
625       if (!lv) {
626         ++(*numTimeouts.contextualLock());
627         continue;
628       }
629
630       // Sleep while holding the lock.
631       //
632       // This will block other threads from acquiring the write lock to add
633       // their thread index to v, but it won't block threads that have entered
634       // the for loop and are trying to acquire a read lock.
635       //
636       // For lock types that give preference to readers rather than writers,
637       // this will tend to serialize all threads on the wlock() above.
638       randomSleep(std::chrono::milliseconds(5), std::chrono::milliseconds(15));
639       auto found = std::find(lv->begin(), lv->end(), threadIdx);
640       CHECK(found != lv->end());
641       break;
642     }
643   };
644
645   static const size_t numThreads = 100;
646   runParallel(numThreads, worker);
647
648   std::vector<int> result;
649   v.swap(result);
650
651   EXPECT_EQ(numThreads, result.size());
652   sort(result.begin(), result.end());
653
654   for (size_t i = 0; i < numThreads; ++i) {
655     EXPECT_EQ(i, result[i]);
656   }
657   // We generally expect a small number of timeouts here.
658   // For locks that give readers preference over writers this should usually
659   // be 0.  With locks that give writers preference we do see a small-ish
660   // number of read timeouts.
661   LOG(INFO) << "testTimedShared: " << *numTimeouts.contextualRLock()
662             << " timeouts";
663 }
664
665 // Testing the deprecated TIMED_SYNCHRONIZED API
666 template <class Mutex> void testTimedSynchronized() {
667   folly::Synchronized<std::vector<int>, Mutex> v;
668   folly::Synchronized<uint64_t, Mutex> numTimeouts;
669
670   auto worker = [&](size_t threadIdx) {
671     // Test operator->
672     v->push_back(2 * threadIdx);
673
674     // Aaand test the TIMED_SYNCHRONIZED macro
675     for (;;)
676       TIMED_SYNCHRONIZED(5, lv, v) {
677         if (lv) {
678           // Sleep for a random time to ensure we trigger timeouts
679           // in other threads
680           randomSleep(
681               std::chrono::milliseconds(5), std::chrono::milliseconds(15));
682           lv->push_back(2 * threadIdx + 1);
683           return;
684         }
685
686         ++(*numTimeouts.contextualLock());
687       }
688   };
689
690   static const size_t numThreads = 100;
691   runParallel(numThreads, worker);
692
693   std::vector<int> result;
694   v.swap(result);
695
696   EXPECT_EQ(2 * numThreads, result.size());
697   sort(result.begin(), result.end());
698
699   for (size_t i = 0; i < 2 * numThreads; ++i) {
700     EXPECT_EQ(i, result[i]);
701   }
702   // We generally expect a large number of number timeouts here.
703   // I'm not adding a check for it since it's theoretically possible that
704   // we might get 0 timeouts depending on the CPU scheduling if our threads
705   // don't get to run very often.
706   LOG(INFO) << "testTimedSynchronized: " << *numTimeouts.contextualRLock()
707             << " timeouts";
708 }
709
710 // Testing the deprecated TIMED_SYNCHRONIZED_CONST API
711 template <class Mutex> void testTimedSynchronizedWithConst() {
712   folly::Synchronized<std::vector<int>, Mutex> v;
713   folly::Synchronized<uint64_t, Mutex> numTimeouts;
714
715   auto worker = [&](size_t threadIdx) {
716     // Test operator->
717     v->push_back(threadIdx);
718
719     // Test TIMED_SYNCHRONIZED_CONST
720     for (;;) {
721       TIMED_SYNCHRONIZED_CONST(10, lv, v) {
722         if (lv) {
723           // Sleep while holding the lock.
724           //
725           // This will block other threads from acquiring the write lock to add
726           // their thread index to v, but it won't block threads that have
727           // entered the for loop and are trying to acquire a read lock.
728           //
729           // For lock types that give preference to readers rather than writers,
730           // this will tend to serialize all threads on the wlock() above.
731           randomSleep(
732               std::chrono::milliseconds(5), std::chrono::milliseconds(15));
733           auto found = std::find(lv->begin(), lv->end(), threadIdx);
734           CHECK(found != lv->end());
735           return;
736         } else {
737           ++(*numTimeouts.contextualLock());
738         }
739       }
740     }
741   };
742
743   static const size_t numThreads = 100;
744   runParallel(numThreads, worker);
745
746   std::vector<int> result;
747   v.swap(result);
748
749   EXPECT_EQ(numThreads, result.size());
750   sort(result.begin(), result.end());
751
752   for (size_t i = 0; i < numThreads; ++i) {
753     EXPECT_EQ(i, result[i]);
754   }
755   // We generally expect a small number of timeouts here.
756   // For locks that give readers preference over writers this should usually
757   // be 0.  With locks that give writers preference we do see a small-ish
758   // number of read timeouts.
759   LOG(INFO) << "testTimedSynchronizedWithConst: "
760             << *numTimeouts.contextualRLock() << " timeouts";
761 }
762
763 template <class Mutex> void testConstCopy() {
764   std::vector<int> input = {1, 2, 3};
765   const folly::Synchronized<std::vector<int>, Mutex> v(input);
766
767   std::vector<int> result;
768
769   v.copy(&result);
770   EXPECT_EQ(input, result);
771
772   result = v.copy();
773   EXPECT_EQ(input, result);
774 }
775
776 struct NotCopiableNotMovable {
777   NotCopiableNotMovable(int, const char*) {}
778   NotCopiableNotMovable(const NotCopiableNotMovable&) = delete;
779   NotCopiableNotMovable& operator=(const NotCopiableNotMovable&) = delete;
780   NotCopiableNotMovable(NotCopiableNotMovable&&) = delete;
781   NotCopiableNotMovable& operator=(NotCopiableNotMovable&&) = delete;
782 };
783
784 template <class Mutex> void testInPlaceConstruction() {
785   // This won't compile without construct_in_place
786   folly::Synchronized<NotCopiableNotMovable> a(
787     folly::construct_in_place, 5, "a"
788   );
789 }
790 }
791 }