-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathtest_thread_safe_cache.cc
173 lines (148 loc) · 4.99 KB
/
test_thread_safe_cache.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
#include <gtest/gtest.h>
#include <xgrammar/xgrammar.h>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <future>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_set>
#include <vector>
#include "support/logging.h"
#include "support/thread_safe_cache.h"
using namespace xgrammar;
static std::atomic_size_t counter{0};
static_assert(
sizeof(CompiledGrammar) >= sizeof(std::size_t),
"Our test requires that CompiledGrammar is at least as large as std::size_t"
);
// simulate a CompiledGrammar object
struct MockGrammar {
std::size_t uuid;
std::byte padding[sizeof(CompiledGrammar) - sizeof(std::size_t)];
};
using namespace std::chrono_literals;
TEST(XGrammarParallelTest, CacheEfficiency) {
auto cache = ThreadSafeCache<std::string, MockGrammar>{[](const std::string&) {
std::this_thread::sleep_for(1s); // simulate a slow operation
MockGrammar g{};
g.uuid = counter++;
return g;
}};
auto futures = std::vector<std::future<std::size_t>>{};
static const auto kGroups = 20;
static const auto kNumThreads = int(std::thread::hardware_concurrency()) * 2;
static const auto kNumTests = kNumThreads / 2;
futures.reserve(kNumThreads);
const auto target = std::chrono::steady_clock::now() + 1s;
// Whatever the execution order, the cache will only call the constructor for kNumTests times.
// As a consequence, the sum of the uuids must be equal to the sum of the first kNumTests
// integers.
const auto tic = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < kNumThreads; ++i) {
futures.push_back(std::async(std::launch::async, [&cache, target, i] {
std::this_thread::sleep_until(target);
auto sum = std::size_t{0};
// Test writing to the cache concurrently
for (auto j = 0; j < kNumTests; ++j) {
const auto key = std::to_string((j + i) % kNumTests);
sum += cache.Get(key).uuid;
}
// Test reading the same keys again
for (auto j = 0; j < kNumTests * (kGroups - 1); ++j) {
const auto key = std::to_string(j % kNumTests);
sum += cache.Get(key).uuid;
}
return sum;
}));
}
// Sum of [0, kNumTests) (I wish i'm not wrong)
const auto kResult = kNumTests * (kNumTests - 1) / 2;
for (auto& future : futures) {
future.wait();
EXPECT_EQ(future.get(), kResult * kGroups);
}
const auto toc = std::chrono::high_resolution_clock::now();
// Skip the first 2s for preparation
const auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(toc - tic - 2s).count();
XGRAMMAR_LOG_INFO << "Duration: " << dur << "ms";
}
// A hook to ensure that the object will not be accessed after its destruction
struct LifeSpanHook {
private:
inline static std::unordered_set<const void*> manager{};
inline static std::mutex mutex{};
static auto unsafe_construct(const LifeSpanHook* ptr) -> void {
// insert will return a pair of iterator and bool
EXPECT_TRUE(manager.insert(ptr).second);
}
static auto unsafe_destruct(const LifeSpanHook* ptr) -> void {
// erase will return 1 if the element is found and removed
EXPECT_TRUE(manager.erase(ptr));
}
static auto unsafe_confirm(const LifeSpanHook* ptr) -> void {
// ensure that the object is still alive
EXPECT_TRUE(manager.find(ptr) != manager.end());
}
public:
LifeSpanHook() {
const auto lock = std::lock_guard{mutex};
unsafe_construct(this);
}
LifeSpanHook(const LifeSpanHook& other) {
const auto lock = std::lock_guard{mutex};
unsafe_construct(this);
unsafe_confirm(&other);
}
auto operator=(const LifeSpanHook& other) -> LifeSpanHook& {
const auto lock = std::lock_guard{mutex};
unsafe_confirm(this);
unsafe_confirm(&other);
return *this;
}
~LifeSpanHook() {
const auto lock = std::lock_guard{mutex};
unsafe_destruct(this);
}
auto check() const -> void {
const auto lock = std::lock_guard{mutex};
unsafe_confirm(this);
}
};
struct TestObject : LifeSpanHook {
private:
std::string name;
public:
TestObject() = default;
TestObject(std::string name) : name(std::move(name)) {}
auto& operator=(std::string name) {
this->check();
this->name = std::move(name);
return *this;
}
operator std::string() const {
this->check();
return this->name;
}
};
TEST(XGrammarParallelTest, CacheCorrectness) {
auto cache = ThreadSafeCache<std::string, TestObject>{[](const std::string& key) {
std::this_thread::sleep_for(1s); // simulate a slow operation
return key;
}};
const auto kNumThreads = int(std::thread::hardware_concurrency()) * 10;
auto futures = std::vector<std::future<std::string>>{};
futures.reserve(kNumThreads);
for (auto i = 0; i < kNumThreads; ++i) {
futures.push_back(std::async(std::launch::async, [&cache, i] {
return std::string(cache.Get(std::to_string(i)));
}));
}
// Wait the futures to block
std::this_thread::sleep_for(100ms);
cache.Clear();
for (auto i = 0; i < kNumThreads; ++i) {
EXPECT_EQ(futures[i].get(), std::to_string(i));
}
}