| 1 | //===-- condition_variable_test.cpp -----------------------------*- C++ -*-===// |
|---|---|
| 2 | // |
| 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 |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "tests/scudo_unit_test.h" |
| 10 | |
| 11 | #include "common.h" |
| 12 | #include "condition_variable.h" |
| 13 | #include "mutex.h" |
| 14 | |
| 15 | #include <thread> |
| 16 | |
| 17 | template <typename ConditionVariableT> void simpleWaitAndNotifyAll() { |
| 18 | constexpr scudo::u32 NumThreads = 2; |
| 19 | constexpr scudo::u32 CounterMax = 1024; |
| 20 | std::thread Threads[NumThreads]; |
| 21 | |
| 22 | scudo::HybridMutex M; |
| 23 | ConditionVariableT CV; |
| 24 | CV.bindTestOnly(M); |
| 25 | scudo::u32 Counter = 0; |
| 26 | |
| 27 | for (scudo::u32 I = 0; I < NumThreads; ++I) { |
| 28 | Threads[I] = std::thread( |
| 29 | [&](scudo::u32 Id) { |
| 30 | do { |
| 31 | scudo::ScopedLock L(M); |
| 32 | if (Counter % NumThreads != Id && Counter < CounterMax) |
| 33 | CV.wait(M); |
| 34 | if (Counter >= CounterMax) { |
| 35 | break; |
| 36 | } else { |
| 37 | ++Counter; |
| 38 | CV.notifyAll(M); |
| 39 | } |
| 40 | } while (true); |
| 41 | }, |
| 42 | I); |
| 43 | } |
| 44 | |
| 45 | for (std::thread &T : Threads) |
| 46 | T.join(); |
| 47 | |
| 48 | EXPECT_EQ(Counter, CounterMax); |
| 49 | } |
| 50 | |
| 51 | TEST(ScudoConditionVariableTest, DummyCVWaitAndNotifyAll) { |
| 52 | simpleWaitAndNotifyAll<scudo::ConditionVariableDummy>(); |
| 53 | } |
| 54 | |
| 55 | #ifdef SCUDO_LINUX |
| 56 | TEST(ScudoConditionVariableTest, LinuxCVWaitAndNotifyAll) { |
| 57 | simpleWaitAndNotifyAll<scudo::ConditionVariableLinux>(); |
| 58 | } |
| 59 | #endif |
| 60 |
