Debian Codegraph @

Source/UnitTests/Common/FlagTest.cpp

raw symbols SCIP
1 // Copyright 2014 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include <array>
5 #include <gtest/gtest.h>
6 #include <thread>
7
8 #include "Common/Flag.h"
9
10 using Common::Flag;
11
12 TEST(Flag, Simple)
13 {
14 Flag f;
15 EXPECT_FALSE(f.IsSet());
16
17 f.Set();
18 EXPECT_TRUE(f.IsSet());
19
20 f.Clear();
21 EXPECT_FALSE(f.IsSet());
22
23 f.Set(false);
24 EXPECT_FALSE(f.IsSet());
25
26 EXPECT_TRUE(f.TestAndSet());
27 EXPECT_TRUE(f.TestAndClear());
28
29 Flag f2(true);
30 EXPECT_TRUE(f2.IsSet());
31 }
32
33 TEST(Flag, MultiThreaded)
34 {
35 Flag f;
36 int count = 0;
37 constexpr int ITERATIONS_COUNT = 100000;
38
39 auto setter = [&] {
40 for (int i = 0; i < ITERATIONS_COUNT; ++i)
41 {
42 while (f.IsSet())
43 ;
44 f.Set();
45 }
46 };
47
48 auto clearer = [&] {
49 for (int i = 0; i < ITERATIONS_COUNT; ++i)
50 {
51 while (!f.IsSet())
52 ;
53 count++;
54 f.Clear();
55 }
56 };
57
58 std::thread setter_thread(setter);
59 std::thread clearer_thread(clearer);
60
61 setter_thread.join();
62 clearer_thread.join();
63
64 EXPECT_EQ(ITERATIONS_COUNT, count);
65 }
66
67 TEST(Flag, SpinLock)
68 {
69 // Uses a flag to implement basic spinlocking using TestAndSet.
70 Flag f;
71 int count = 0;
72 constexpr int ITERATIONS_COUNT = 5000;
73 constexpr int THREADS_COUNT = 50;
74
75 auto adder_func = [&] {
76 for (int i = 0; i < ITERATIONS_COUNT; ++i)
77 {
78 // Acquire the spinlock.
79 while (!f.TestAndSet())
80 ;
81 count++;
82 f.Clear();
83 }
84 };
85
86 std::array<std::thread, THREADS_COUNT> threads;
87 for (auto& th : threads)
88 th = std::thread(adder_func);
89 for (auto& th : threads)
90 th.join();
91
92 EXPECT_EQ(ITERATIONS_COUNT * THREADS_COUNT, count);
93 }