1 //===-- mutex_test.cpp ------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "gwp_asan/mutex.h"
10 #include "gwp_asan/tests/harness.h"
17 using gwp_asan::Mutex
;
18 using gwp_asan::ScopedLock
;
20 TEST(GwpAsanMutexTest
, LockUnlockTest
) {
23 ASSERT_TRUE(Mu
.tryLock());
24 ASSERT_FALSE(Mu
.tryLock());
30 // Ensure that the mutex actually unlocked.
31 ASSERT_TRUE(Mu
.tryLock());
35 TEST(GwpAsanMutexTest
, ScopedLockUnlockTest
) {
38 // Locking will fail here if the scoped lock failed to unlock.
39 EXPECT_TRUE(Mu
.tryLock());
44 EXPECT_FALSE(Mu
.tryLock()); // Check that the c'tor did lock.
46 // Manually unlock and check that this succeeds.
48 EXPECT_TRUE(Mu
.tryLock()); // Manually lock.
50 EXPECT_TRUE(Mu
.tryLock()); // Assert that the scoped destructor did unlock.
54 static void synchronousIncrementTask(std::atomic
<bool> *StartingGun
, Mutex
*Mu
,
56 unsigned NumIterations
) {
57 while (!StartingGun
) {
58 // Wait for starting gun.
60 for (unsigned i
= 0; i
< NumIterations
; ++i
) {
66 static void runSynchronisedTest(unsigned NumThreads
, unsigned CounterMax
) {
67 std::vector
<std::thread
> Threads
;
69 ASSERT_TRUE(CounterMax
% NumThreads
== 0);
71 std::atomic
<bool> StartingGun
{false};
75 for (unsigned i
= 0; i
< NumThreads
; ++i
)
76 Threads
.emplace_back(synchronousIncrementTask
, &StartingGun
, &Mu
, &Counter
,
77 CounterMax
/ NumThreads
);
80 for (auto &T
: Threads
)
83 EXPECT_EQ(CounterMax
, Counter
);
86 TEST(GwpAsanMutexTest
, SynchronisedCounterTest
) {
87 runSynchronisedTest(4, 1000000);
88 runSynchronisedTest(100, 1000000);