forked from abseil/abseil-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex_test.cc
1537 lines (1342 loc) · 47.5 KB
/
mutex_test.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/synchronization/mutex.h"
#ifdef WIN32
#include <windows.h>
#endif
#include <algorithm>
#include <atomic>
#include <cstdlib>
#include <functional>
#include <memory>
#include <random>
#include <string>
#include <thread> // NOLINT(build/c++11)
#include <vector>
#include "gtest/gtest.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/internal/sysinfo.h"
#include "absl/memory/memory.h"
#include "absl/synchronization/internal/thread_pool.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
namespace {
// TODO(dmauro): Replace with a commandline flag.
static constexpr bool kExtendedTest = false;
std::unique_ptr<absl::synchronization_internal::ThreadPool> CreatePool(
int threads) {
return absl::make_unique<absl::synchronization_internal::ThreadPool>(threads);
}
std::unique_ptr<absl::synchronization_internal::ThreadPool>
CreateDefaultPool() {
return CreatePool(kExtendedTest ? 32 : 10);
}
// Hack to schedule a function to run on a thread pool thread after a
// duration has elapsed.
static void ScheduleAfter(absl::synchronization_internal::ThreadPool *tp,
const std::function<void()> &func,
absl::Duration after) {
tp->Schedule([func, after] {
absl::SleepFor(after);
func();
});
}
struct TestContext {
int iterations;
int threads;
int g0; // global 0
int g1; // global 1
absl::Mutex mu;
absl::CondVar cv;
};
// To test whether the invariant check call occurs
static std::atomic<bool> invariant_checked;
static bool GetInvariantChecked() {
return invariant_checked.load(std::memory_order_relaxed);
}
static void SetInvariantChecked(bool new_value) {
invariant_checked.store(new_value, std::memory_order_relaxed);
}
static void CheckSumG0G1(void *v) {
TestContext *cxt = static_cast<TestContext *>(v);
ABSL_RAW_CHECK(cxt->g0 == -cxt->g1, "Error in CheckSumG0G1");
SetInvariantChecked(true);
}
static void TestMu(TestContext *cxt, int c) {
for (int i = 0; i != cxt->iterations; i++) {
absl::MutexLock l(&cxt->mu);
int a = cxt->g0 + 1;
cxt->g0 = a;
cxt->g1--;
}
}
static void TestTry(TestContext *cxt, int c) {
for (int i = 0; i != cxt->iterations; i++) {
do {
std::this_thread::yield();
} while (!cxt->mu.TryLock());
int a = cxt->g0 + 1;
cxt->g0 = a;
cxt->g1--;
cxt->mu.Unlock();
}
}
static void TestR20ms(TestContext *cxt, int c) {
for (int i = 0; i != cxt->iterations; i++) {
absl::ReaderMutexLock l(&cxt->mu);
absl::SleepFor(absl::Milliseconds(20));
cxt->mu.AssertReaderHeld();
}
}
static void TestRW(TestContext *cxt, int c) {
if ((c & 1) == 0) {
for (int i = 0; i != cxt->iterations; i++) {
absl::WriterMutexLock l(&cxt->mu);
cxt->g0++;
cxt->g1--;
cxt->mu.AssertHeld();
cxt->mu.AssertReaderHeld();
}
} else {
for (int i = 0; i != cxt->iterations; i++) {
absl::ReaderMutexLock l(&cxt->mu);
ABSL_RAW_CHECK(cxt->g0 == -cxt->g1, "Error in TestRW");
cxt->mu.AssertReaderHeld();
}
}
}
struct MyContext {
int target;
TestContext *cxt;
bool MyTurn();
};
bool MyContext::MyTurn() {
TestContext *cxt = this->cxt;
return cxt->g0 == this->target || cxt->g0 == cxt->iterations;
}
static void TestAwait(TestContext *cxt, int c) {
MyContext mc;
mc.target = c;
mc.cxt = cxt;
absl::MutexLock l(&cxt->mu);
cxt->mu.AssertHeld();
while (cxt->g0 < cxt->iterations) {
cxt->mu.Await(absl::Condition(&mc, &MyContext::MyTurn));
ABSL_RAW_CHECK(mc.MyTurn(), "Error in TestAwait");
cxt->mu.AssertHeld();
if (cxt->g0 < cxt->iterations) {
int a = cxt->g0 + 1;
cxt->g0 = a;
mc.target += cxt->threads;
}
}
}
static void TestSignalAll(TestContext *cxt, int c) {
int target = c;
absl::MutexLock l(&cxt->mu);
cxt->mu.AssertHeld();
while (cxt->g0 < cxt->iterations) {
while (cxt->g0 != target && cxt->g0 != cxt->iterations) {
cxt->cv.Wait(&cxt->mu);
}
if (cxt->g0 < cxt->iterations) {
int a = cxt->g0 + 1;
cxt->g0 = a;
cxt->cv.SignalAll();
target += cxt->threads;
}
}
}
static void TestSignal(TestContext *cxt, int c) {
ABSL_RAW_CHECK(cxt->threads == 2, "TestSignal should use 2 threads");
int target = c;
absl::MutexLock l(&cxt->mu);
cxt->mu.AssertHeld();
while (cxt->g0 < cxt->iterations) {
while (cxt->g0 != target && cxt->g0 != cxt->iterations) {
cxt->cv.Wait(&cxt->mu);
}
if (cxt->g0 < cxt->iterations) {
int a = cxt->g0 + 1;
cxt->g0 = a;
cxt->cv.Signal();
target += cxt->threads;
}
}
}
static void TestCVTimeout(TestContext *cxt, int c) {
int target = c;
absl::MutexLock l(&cxt->mu);
cxt->mu.AssertHeld();
while (cxt->g0 < cxt->iterations) {
while (cxt->g0 != target && cxt->g0 != cxt->iterations) {
cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(100));
}
if (cxt->g0 < cxt->iterations) {
int a = cxt->g0 + 1;
cxt->g0 = a;
cxt->cv.SignalAll();
target += cxt->threads;
}
}
}
static bool G0GE2(TestContext *cxt) { return cxt->g0 >= 2; }
static void TestTime(TestContext *cxt, int c, bool use_cv) {
ABSL_RAW_CHECK(cxt->iterations == 1, "TestTime should only use 1 iteration");
ABSL_RAW_CHECK(cxt->threads > 2, "TestTime should use more than 2 threads");
const bool kFalse = false;
absl::Condition false_cond(&kFalse);
absl::Condition g0ge2(G0GE2, cxt);
if (c == 0) {
absl::MutexLock l(&cxt->mu);
absl::Time start = absl::Now();
if (use_cv) {
cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(1));
} else {
ABSL_RAW_CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(1)),
"TestTime failed");
}
absl::Duration elapsed = absl::Now() - start;
ABSL_RAW_CHECK(
absl::Seconds(0.9) <= elapsed && elapsed <= absl::Seconds(2.0),
"TestTime failed");
ABSL_RAW_CHECK(cxt->g0 == 1, "TestTime failed");
start = absl::Now();
if (use_cv) {
cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(1));
} else {
ABSL_RAW_CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(1)),
"TestTime failed");
}
elapsed = absl::Now() - start;
ABSL_RAW_CHECK(
absl::Seconds(0.9) <= elapsed && elapsed <= absl::Seconds(2.0),
"TestTime failed");
cxt->g0++;
if (use_cv) {
cxt->cv.Signal();
}
start = absl::Now();
if (use_cv) {
cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(4));
} else {
ABSL_RAW_CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(4)),
"TestTime failed");
}
elapsed = absl::Now() - start;
ABSL_RAW_CHECK(
absl::Seconds(3.9) <= elapsed && elapsed <= absl::Seconds(6.0),
"TestTime failed");
ABSL_RAW_CHECK(cxt->g0 >= 3, "TestTime failed");
start = absl::Now();
if (use_cv) {
cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(1));
} else {
ABSL_RAW_CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(1)),
"TestTime failed");
}
elapsed = absl::Now() - start;
ABSL_RAW_CHECK(
absl::Seconds(0.9) <= elapsed && elapsed <= absl::Seconds(2.0),
"TestTime failed");
if (use_cv) {
cxt->cv.SignalAll();
}
start = absl::Now();
if (use_cv) {
cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(1));
} else {
ABSL_RAW_CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(1)),
"TestTime failed");
}
elapsed = absl::Now() - start;
ABSL_RAW_CHECK(absl::Seconds(0.9) <= elapsed &&
elapsed <= absl::Seconds(2.0), "TestTime failed");
ABSL_RAW_CHECK(cxt->g0 == cxt->threads, "TestTime failed");
} else if (c == 1) {
absl::MutexLock l(&cxt->mu);
const absl::Time start = absl::Now();
if (use_cv) {
cxt->cv.WaitWithTimeout(&cxt->mu, absl::Milliseconds(500));
} else {
ABSL_RAW_CHECK(
!cxt->mu.AwaitWithTimeout(false_cond, absl::Milliseconds(500)),
"TestTime failed");
}
const absl::Duration elapsed = absl::Now() - start;
ABSL_RAW_CHECK(
absl::Seconds(0.4) <= elapsed && elapsed <= absl::Seconds(0.9),
"TestTime failed");
cxt->g0++;
} else if (c == 2) {
absl::MutexLock l(&cxt->mu);
if (use_cv) {
while (cxt->g0 < 2) {
cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(100));
}
} else {
ABSL_RAW_CHECK(cxt->mu.AwaitWithTimeout(g0ge2, absl::Seconds(100)),
"TestTime failed");
}
cxt->g0++;
} else {
absl::MutexLock l(&cxt->mu);
if (use_cv) {
while (cxt->g0 < 2) {
cxt->cv.Wait(&cxt->mu);
}
} else {
cxt->mu.Await(g0ge2);
}
cxt->g0++;
}
}
static void TestMuTime(TestContext *cxt, int c) { TestTime(cxt, c, false); }
static void TestCVTime(TestContext *cxt, int c) { TestTime(cxt, c, true); }
static void EndTest(int *c0, int *c1, absl::Mutex *mu, absl::CondVar *cv,
const std::function<void(int)>& cb) {
mu->Lock();
int c = (*c0)++;
mu->Unlock();
cb(c);
absl::MutexLock l(mu);
(*c1)++;
cv->Signal();
}
// Code common to RunTest() and RunTestWithInvariantDebugging().
static int RunTestCommon(TestContext *cxt, void (*test)(TestContext *cxt, int),
int threads, int iterations, int operations) {
absl::Mutex mu2;
absl::CondVar cv2;
int c0 = 0;
int c1 = 0;
cxt->g0 = 0;
cxt->g1 = 0;
cxt->iterations = iterations;
cxt->threads = threads;
absl::synchronization_internal::ThreadPool tp(threads);
for (int i = 0; i != threads; i++) {
tp.Schedule(std::bind(&EndTest, &c0, &c1, &mu2, &cv2,
std::function<void(int)>(
std::bind(test, cxt, std::placeholders::_1))));
}
mu2.Lock();
while (c1 != threads) {
cv2.Wait(&mu2);
}
mu2.Unlock();
return cxt->g0;
}
// Basis for the parameterized tests configured below.
static int RunTest(void (*test)(TestContext *cxt, int), int threads,
int iterations, int operations) {
TestContext cxt;
return RunTestCommon(&cxt, test, threads, iterations, operations);
}
// Like RunTest(), but sets an invariant on the tested Mutex and
// verifies that the invariant check happened. The invariant function
// will be passed the TestContext* as its arg and must call
// SetInvariantChecked(true);
#if !defined(ABSL_MUTEX_ENABLE_INVARIANT_DEBUGGING_NOT_IMPLEMENTED)
static int RunTestWithInvariantDebugging(void (*test)(TestContext *cxt, int),
int threads, int iterations,
int operations,
void (*invariant)(void *)) {
absl::EnableMutexInvariantDebugging(true);
SetInvariantChecked(false);
TestContext cxt;
cxt.mu.EnableInvariantDebugging(invariant, &cxt);
int ret = RunTestCommon(&cxt, test, threads, iterations, operations);
ABSL_RAW_CHECK(GetInvariantChecked(), "Invariant not checked");
absl::EnableMutexInvariantDebugging(false); // Restore.
return ret;
}
#endif
// --------------------------------------------------------
// Test for fix of bug in TryRemove()
struct TimeoutBugStruct {
absl::Mutex mu;
bool a;
int a_waiter_count;
};
static void WaitForA(TimeoutBugStruct *x) {
x->mu.LockWhen(absl::Condition(&x->a));
x->a_waiter_count--;
x->mu.Unlock();
}
static bool NoAWaiters(TimeoutBugStruct *x) { return x->a_waiter_count == 0; }
// Test that a CondVar.Wait(&mutex) can un-block a call to mutex.Await() in
// another thread.
TEST(Mutex, CondVarWaitSignalsAwait) {
// Use a struct so the lock annotations apply.
struct {
absl::Mutex barrier_mu;
bool barrier GUARDED_BY(barrier_mu) = false;
absl::Mutex release_mu;
bool release GUARDED_BY(release_mu) = false;
absl::CondVar released_cv;
} state;
auto pool = CreateDefaultPool();
// Thread A. Sets barrier, waits for release using Mutex::Await, then
// signals released_cv.
pool->Schedule([&state] {
state.release_mu.Lock();
state.barrier_mu.Lock();
state.barrier = true;
state.barrier_mu.Unlock();
state.release_mu.Await(absl::Condition(&state.release));
state.released_cv.Signal();
state.release_mu.Unlock();
});
state.barrier_mu.LockWhen(absl::Condition(&state.barrier));
state.barrier_mu.Unlock();
state.release_mu.Lock();
// Thread A is now blocked on release by way of Mutex::Await().
// Set release. Calling released_cv.Wait() should un-block thread A,
// which will signal released_cv. If not, the test will hang.
state.release = true;
state.released_cv.Wait(&state.release_mu);
state.release_mu.Unlock();
}
// Test that a CondVar.WaitWithTimeout(&mutex) can un-block a call to
// mutex.Await() in another thread.
TEST(Mutex, CondVarWaitWithTimeoutSignalsAwait) {
// Use a struct so the lock annotations apply.
struct {
absl::Mutex barrier_mu;
bool barrier GUARDED_BY(barrier_mu) = false;
absl::Mutex release_mu;
bool release GUARDED_BY(release_mu) = false;
absl::CondVar released_cv;
} state;
auto pool = CreateDefaultPool();
// Thread A. Sets barrier, waits for release using Mutex::Await, then
// signals released_cv.
pool->Schedule([&state] {
state.release_mu.Lock();
state.barrier_mu.Lock();
state.barrier = true;
state.barrier_mu.Unlock();
state.release_mu.Await(absl::Condition(&state.release));
state.released_cv.Signal();
state.release_mu.Unlock();
});
state.barrier_mu.LockWhen(absl::Condition(&state.barrier));
state.barrier_mu.Unlock();
state.release_mu.Lock();
// Thread A is now blocked on release by way of Mutex::Await().
// Set release. Calling released_cv.Wait() should un-block thread A,
// which will signal released_cv. If not, the test will hang.
state.release = true;
EXPECT_TRUE(
!state.released_cv.WaitWithTimeout(&state.release_mu, absl::Seconds(10)))
<< "; Unrecoverable test failure: CondVar::WaitWithTimeout did not "
"unblock the absl::Mutex::Await call in another thread.";
state.release_mu.Unlock();
}
// Test for regression of a bug in loop of TryRemove()
TEST(Mutex, MutexTimeoutBug) {
auto tp = CreateDefaultPool();
TimeoutBugStruct x;
x.a = false;
x.a_waiter_count = 2;
tp->Schedule(std::bind(&WaitForA, &x));
tp->Schedule(std::bind(&WaitForA, &x));
absl::SleepFor(absl::Seconds(1)); // Allow first two threads to hang.
// The skip field of the second will point to the first because there are
// only two.
// Now cause a thread waiting on an always-false to time out
// This would deadlock when the bug was present.
bool always_false = false;
x.mu.LockWhenWithTimeout(absl::Condition(&always_false),
absl::Milliseconds(500));
// if we get here, the bug is not present. Cleanup the state.
x.a = true; // wakeup the two waiters on A
x.mu.Await(absl::Condition(&NoAWaiters, &x)); // wait for them to exit
x.mu.Unlock();
}
struct CondVarWaitDeadlock : testing::TestWithParam<int> {
absl::Mutex mu;
absl::CondVar cv;
bool cond1 = false;
bool cond2 = false;
bool read_lock1;
bool read_lock2;
bool signal_unlocked;
CondVarWaitDeadlock() {
read_lock1 = GetParam() & (1 << 0);
read_lock2 = GetParam() & (1 << 1);
signal_unlocked = GetParam() & (1 << 2);
}
void Waiter1() {
if (read_lock1) {
mu.ReaderLock();
while (!cond1) {
cv.Wait(&mu);
}
mu.ReaderUnlock();
} else {
mu.Lock();
while (!cond1) {
cv.Wait(&mu);
}
mu.Unlock();
}
}
void Waiter2() {
if (read_lock2) {
mu.ReaderLockWhen(absl::Condition(&cond2));
mu.ReaderUnlock();
} else {
mu.LockWhen(absl::Condition(&cond2));
mu.Unlock();
}
}
};
// Test for a deadlock bug in Mutex::Fer().
// The sequence of events that lead to the deadlock is:
// 1. waiter1 blocks on cv in read mode (mu bits = 0).
// 2. waiter2 blocks on mu in either mode (mu bits = kMuWait).
// 3. main thread locks mu, sets cond1, unlocks mu (mu bits = kMuWait).
// 4. main thread signals on cv and this eventually calls Mutex::Fer().
// Currently Fer wakes waiter1 since mu bits = kMuWait (mutex is unlocked).
// Before the bug fix Fer neither woke waiter1 nor queued it on mutex,
// which resulted in deadlock.
TEST_P(CondVarWaitDeadlock, Test) {
auto waiter1 = CreatePool(1);
auto waiter2 = CreatePool(1);
waiter1->Schedule([this] { this->Waiter1(); });
waiter2->Schedule([this] { this->Waiter2(); });
// Wait while threads block (best-effort is fine).
absl::SleepFor(absl::Milliseconds(100));
// Wake condwaiter.
mu.Lock();
cond1 = true;
if (signal_unlocked) {
mu.Unlock();
cv.Signal();
} else {
cv.Signal();
mu.Unlock();
}
waiter1.reset(); // "join" waiter1
// Wake waiter.
mu.Lock();
cond2 = true;
mu.Unlock();
waiter2.reset(); // "join" waiter2
}
INSTANTIATE_TEST_CASE_P(CondVarWaitDeadlockTest, CondVarWaitDeadlock,
::testing::Range(0, 8),
::testing::PrintToStringParamName());
// --------------------------------------------------------
// Test for fix of bug in DequeueAllWakeable()
// Bug was that if there was more than one waiting reader
// and all should be woken, the most recently blocked one
// would not be.
struct DequeueAllWakeableBugStruct {
absl::Mutex mu;
absl::Mutex mu2; // protects all fields below
int unfinished_count; // count of unfinished readers; under mu2
bool done1; // unfinished_count == 0; under mu2
int finished_count; // count of finished readers, under mu2
bool done2; // finished_count == 0; under mu2
};
// Test for regression of a bug in loop of DequeueAllWakeable()
static void AcquireAsReader(DequeueAllWakeableBugStruct *x) {
x->mu.ReaderLock();
x->mu2.Lock();
x->unfinished_count--;
x->done1 = (x->unfinished_count == 0);
x->mu2.Unlock();
// make sure that both readers acquired mu before we release it.
absl::SleepFor(absl::Seconds(2));
x->mu.ReaderUnlock();
x->mu2.Lock();
x->finished_count--;
x->done2 = (x->finished_count == 0);
x->mu2.Unlock();
}
// Test for regression of a bug in loop of DequeueAllWakeable()
TEST(Mutex, MutexReaderWakeupBug) {
auto tp = CreateDefaultPool();
DequeueAllWakeableBugStruct x;
x.unfinished_count = 2;
x.done1 = false;
x.finished_count = 2;
x.done2 = false;
x.mu.Lock(); // acquire mu exclusively
// queue two thread that will block on reader locks on x.mu
tp->Schedule(std::bind(&AcquireAsReader, &x));
tp->Schedule(std::bind(&AcquireAsReader, &x));
absl::SleepFor(absl::Seconds(1)); // give time for reader threads to block
x.mu.Unlock(); // wake them up
// both readers should finish promptly
EXPECT_TRUE(
x.mu2.LockWhenWithTimeout(absl::Condition(&x.done1), absl::Seconds(10)));
x.mu2.Unlock();
EXPECT_TRUE(
x.mu2.LockWhenWithTimeout(absl::Condition(&x.done2), absl::Seconds(10)));
x.mu2.Unlock();
}
struct LockWhenTestStruct {
absl::Mutex mu1;
bool cond = false;
absl::Mutex mu2;
bool waiting = false;
};
static bool LockWhenTestIsCond(LockWhenTestStruct* s) {
s->mu2.Lock();
s->waiting = true;
s->mu2.Unlock();
return s->cond;
}
static void LockWhenTestWaitForIsCond(LockWhenTestStruct* s) {
s->mu1.LockWhen(absl::Condition(&LockWhenTestIsCond, s));
s->mu1.Unlock();
}
TEST(Mutex, LockWhen) {
LockWhenTestStruct s;
std::thread t(LockWhenTestWaitForIsCond, &s);
s.mu2.LockWhen(absl::Condition(&s.waiting));
s.mu2.Unlock();
s.mu1.Lock();
s.cond = true;
s.mu1.Unlock();
t.join();
}
// --------------------------------------------------------
// The following test requires Mutex::ReaderLock to be a real shared
// lock, which is not the case in all builds.
#if !defined(ABSL_MUTEX_READER_LOCK_IS_EXCLUSIVE)
// Test for fix of bug in UnlockSlow() that incorrectly decremented the reader
// count when putting a thread to sleep waiting for a false condition when the
// lock was not held.
// For this bug to strike, we make a thread wait on a free mutex with no
// waiters by causing its wakeup condition to be false. Then the
// next two acquirers must be readers. The bug causes the lock
// to be released when one reader unlocks, rather than both.
struct ReaderDecrementBugStruct {
bool cond; // to delay first thread (under mu)
int done; // reference count (under mu)
absl::Mutex mu;
bool waiting_on_cond; // under mu2
bool have_reader_lock; // under mu2
bool complete; // under mu2
absl::Mutex mu2; // > mu
};
// L >= mu, L < mu_waiting_on_cond
static bool IsCond(void *v) {
ReaderDecrementBugStruct *x = reinterpret_cast<ReaderDecrementBugStruct *>(v);
x->mu2.Lock();
x->waiting_on_cond = true;
x->mu2.Unlock();
return x->cond;
}
// L >= mu
static bool AllDone(void *v) {
ReaderDecrementBugStruct *x = reinterpret_cast<ReaderDecrementBugStruct *>(v);
return x->done == 0;
}
// L={}
static void WaitForCond(ReaderDecrementBugStruct *x) {
absl::Mutex dummy;
absl::MutexLock l(&dummy);
x->mu.LockWhen(absl::Condition(&IsCond, x));
x->done--;
x->mu.Unlock();
}
// L={}
static void GetReadLock(ReaderDecrementBugStruct *x) {
x->mu.ReaderLock();
x->mu2.Lock();
x->have_reader_lock = true;
x->mu2.Await(absl::Condition(&x->complete));
x->mu2.Unlock();
x->mu.ReaderUnlock();
x->mu.Lock();
x->done--;
x->mu.Unlock();
}
// Test for reader counter being decremented incorrectly by waiter
// with false condition.
TEST(Mutex, MutexReaderDecrementBug) NO_THREAD_SAFETY_ANALYSIS {
ReaderDecrementBugStruct x;
x.cond = false;
x.waiting_on_cond = false;
x.have_reader_lock = false;
x.complete = false;
x.done = 2; // initial ref count
// Run WaitForCond() and wait for it to sleep
std::thread thread1(WaitForCond, &x);
x.mu2.LockWhen(absl::Condition(&x.waiting_on_cond));
x.mu2.Unlock();
// Run GetReadLock(), and wait for it to get the read lock
std::thread thread2(GetReadLock, &x);
x.mu2.LockWhen(absl::Condition(&x.have_reader_lock));
x.mu2.Unlock();
// Get the reader lock ourselves, and release it.
x.mu.ReaderLock();
x.mu.ReaderUnlock();
// The lock should be held in read mode by GetReadLock().
// If we have the bug, the lock will be free.
x.mu.AssertReaderHeld();
// Wake up all the threads.
x.mu2.Lock();
x.complete = true;
x.mu2.Unlock();
// TODO(delesley): turn on analysis once lock upgrading is supported.
// (This call upgrades the lock from shared to exclusive.)
x.mu.Lock();
x.cond = true;
x.mu.Await(absl::Condition(&AllDone, &x));
x.mu.Unlock();
thread1.join();
thread2.join();
}
#endif // !ABSL_MUTEX_READER_LOCK_IS_EXCLUSIVE
// Test that we correctly handle the situation when a lock is
// held and then destroyed (w/o unlocking).
TEST(Mutex, LockedMutexDestructionBug) NO_THREAD_SAFETY_ANALYSIS {
for (int i = 0; i != 10; i++) {
// Create, lock and destroy 10 locks.
const int kNumLocks = 10;
auto mu = absl::make_unique<absl::Mutex[]>(kNumLocks);
for (int j = 0; j != kNumLocks; j++) {
if ((j % 2) == 0) {
mu[j].WriterLock();
} else {
mu[j].ReaderLock();
}
}
}
}
// --------------------------------------------------------
// Test for bug with pattern of readers using a condvar. The bug was that if a
// reader went to sleep on a condition variable while one or more other readers
// held the lock, but there were no waiters, the reader count (held in the
// mutex word) would be lost. (This is because Enqueue() had at one time
// always placed the thread on the Mutex queue. Later (CL 4075610), to
// tolerate re-entry into Mutex from a Condition predicate, Enqueue() was
// changed so that it could also place a thread on a condition-variable. This
// introduced the case where Enqueue() returned with an empty queue, and this
// case was handled incorrectly in one place.)
static void ReaderForReaderOnCondVar(absl::Mutex *mu, absl::CondVar *cv,
int *running) {
std::random_device dev;
std::mt19937 gen(dev());
std::uniform_int_distribution<int> random_millis(0, 15);
mu->ReaderLock();
while (*running == 3) {
absl::SleepFor(absl::Milliseconds(random_millis(gen)));
cv->WaitWithTimeout(mu, absl::Milliseconds(random_millis(gen)));
}
mu->ReaderUnlock();
mu->Lock();
(*running)--;
mu->Unlock();
}
struct True {
template <class... Args>
bool operator()(Args...) const {
return true;
}
};
struct DerivedTrue : True {};
TEST(Mutex, FunctorCondition) {
{ // Variadic
True f;
EXPECT_TRUE(absl::Condition(&f).Eval());
}
{ // Inherited
DerivedTrue g;
EXPECT_TRUE(absl::Condition(&g).Eval());
}
{ // lambda
int value = 3;
auto is_zero = [&value] { return value == 0; };
absl::Condition c(&is_zero);
EXPECT_FALSE(c.Eval());
value = 0;
EXPECT_TRUE(c.Eval());
}
{ // bind
int value = 0;
auto is_positive = std::bind(std::less<int>(), 0, std::cref(value));
absl::Condition c(&is_positive);
EXPECT_FALSE(c.Eval());
value = 1;
EXPECT_TRUE(c.Eval());
}
{ // std::function
int value = 3;
std::function<bool()> is_zero = [&value] { return value == 0; };
absl::Condition c(&is_zero);
EXPECT_FALSE(c.Eval());
value = 0;
EXPECT_TRUE(c.Eval());
}
}
static bool IntIsZero(int *x) { return *x == 0; }
// Test for reader waiting condition variable when there are other readers
// but no waiters.
TEST(Mutex, TestReaderOnCondVar) {
auto tp = CreateDefaultPool();
absl::Mutex mu;
absl::CondVar cv;
int running = 3;
tp->Schedule(std::bind(&ReaderForReaderOnCondVar, &mu, &cv, &running));
tp->Schedule(std::bind(&ReaderForReaderOnCondVar, &mu, &cv, &running));
absl::SleepFor(absl::Seconds(2));
mu.Lock();
running--;
mu.Await(absl::Condition(&IntIsZero, &running));
mu.Unlock();
}
// --------------------------------------------------------
struct AcquireFromConditionStruct {
absl::Mutex mu0; // protects value, done
int value; // times condition function is called; under mu0,
bool done; // done with test? under mu0
absl::Mutex mu1; // used to attempt to mess up state of mu0
absl::CondVar cv; // so the condition function can be invoked from
// CondVar::Wait().
};
static bool ConditionWithAcquire(AcquireFromConditionStruct *x) {
x->value++; // count times this function is called
if (x->value == 2 || x->value == 3) {
// On the second and third invocation of this function, sleep for 100ms,
// but with the side-effect of altering the state of a Mutex other than
// than one for which this is a condition. The spec now explicitly allows
// this side effect; previously it did not. it was illegal.
bool always_false = false;
x->mu1.LockWhenWithTimeout(absl::Condition(&always_false),
absl::Milliseconds(100));
x->mu1.Unlock();
}
ABSL_RAW_CHECK(x->value < 4, "should not be invoked a fourth time");
// We arrange for the condition to return true on only the 2nd and 3rd calls.
return x->value == 2 || x->value == 3;
}
static void WaitForCond2(AcquireFromConditionStruct *x) {
// wait for cond0 to become true
x->mu0.LockWhen(absl::Condition(&ConditionWithAcquire, x));
x->done = true;
x->mu0.Unlock();
}
// Test for Condition whose function acquires other Mutexes
TEST(Mutex, AcquireFromCondition) {
auto tp = CreateDefaultPool();
AcquireFromConditionStruct x;
x.value = 0;
x.done = false;
tp->Schedule(
std::bind(&WaitForCond2, &x)); // run WaitForCond2() in a thread T
// T will hang because the first invocation of ConditionWithAcquire() will
// return false.
absl::SleepFor(absl::Milliseconds(500)); // allow T time to hang
x.mu0.Lock();
x.cv.WaitWithTimeout(&x.mu0, absl::Milliseconds(500)); // wake T
// T will be woken because the Wait() will call ConditionWithAcquire()
// for the second time, and it will return true.
x.mu0.Unlock();
// T will then acquire the lock and recheck its own condition.
// It will find the condition true, as this is the third invocation,
// but the use of another Mutex by the calling function will
// cause the old mutex implementation to think that the outer
// LockWhen() has timed out because the inner LockWhenWithTimeout() did.
// T will then check the condition a fourth time because it finds a
// timeout occurred. This should not happen in the new
// implementation that allows the Condition function to use Mutexes.
// It should also succeed, even though the Condition function
// is being invoked from CondVar::Wait, and thus this thread
// is conceptually waiting both on the condition variable, and on mu2.
x.mu0.LockWhen(absl::Condition(&x.done));
x.mu0.Unlock();
}
// The deadlock detector is not part of non-prod builds, so do not test it.
#if !defined(ABSL_INTERNAL_USE_NONPROD_MUTEX)