summaryrefslogtreecommitdiff
path: root/Source/UnitTests/Common/FlagTest.cpp
blob: 8d43d107916faec5949e52c2bb3c3322f7a5d688 (plain)
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
// Copyright 2014 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#include <array>
#include <thread>
#include <gtest/gtest.h>

#include "Common/Flag.h"

using Common::Flag;

TEST(Flag, Simple)
{
	Flag f;
	EXPECT_FALSE(f.IsSet());

	f.Set();
	EXPECT_TRUE(f.IsSet());

	f.Clear();
	EXPECT_FALSE(f.IsSet());

	f.Set(false);
	EXPECT_FALSE(f.IsSet());

	EXPECT_TRUE(f.TestAndSet());
	EXPECT_TRUE(f.TestAndClear());

	Flag f2(true);
	EXPECT_TRUE(f2.IsSet());
}

TEST(Flag, MultiThreaded)
{
	Flag f;
	int count = 0;
	const int ITERATIONS_COUNT = 100000;

	auto setter = [&]() {
		for (int i = 0; i < ITERATIONS_COUNT; ++i)
		{
			while (f.IsSet());
			f.Set();
		}
	};

	auto clearer = [&]() {
		for (int i = 0; i < ITERATIONS_COUNT; ++i)
		{
			while (!f.IsSet());
			count++;
			f.Clear();
		}
	};

	std::thread setter_thread(setter);
	std::thread clearer_thread(clearer);

	setter_thread.join();
	clearer_thread.join();

	EXPECT_EQ(ITERATIONS_COUNT, count);
}

TEST(Flag, SpinLock)
{
	// Uses a flag to implement basic spinlocking using TestAndSet.
	Flag f;
	int count = 0;
	const int ITERATIONS_COUNT = 5000;
	const int THREADS_COUNT = 50;

	auto adder_func = [&]() {
		for (int i = 0; i < ITERATIONS_COUNT; ++i)
		{
			// Acquire the spinlock.
			while (!f.TestAndSet());
			count++;
			f.Clear();
		}
	};

	std::array<std::thread, THREADS_COUNT> threads;
	for (auto& th : threads)
		th = std::thread(adder_func);
	for (auto& th : threads)
		th.join();

	EXPECT_EQ(ITERATIONS_COUNT * THREADS_COUNT, count);
}