-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_lru.cpp
More file actions
95 lines (82 loc) · 3.15 KB
/
test_lru.cpp
File metadata and controls
95 lines (82 loc) · 3.15 KB
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
#include <iostream>
#include <thread>
#include <vector>
#include <random>
#include <cassert>
#include <chrono>
#include <atomic>
#include "thread_safe_lru_cache.h" // 假设上面的 LRU 实现在此头文件中
void run_multithread_test() {
const size_t CAPACITY = 100;
const int NUM_KEYS = 200; // key 范围: 0 ~ 199
const int NUM_WRITERS = 4;
const int NUM_READERS = 8;
const int DURATION_SEC = 3; // 运行 3 秒
ShardedThreadSafeLRUCache<int, int> cache(CAPACITY);
std::atomic<bool> stop{false};
std::vector<std::thread> threads;
// === 写线程:不断 put ===
for (int t = 0; t < NUM_WRITERS; ++t) {
threads.emplace_back([&cache, &stop, t, NUM_KEYS]() {
std::mt19937 gen(t); // 每个线程独立随机种子
std::uniform_int_distribution<> dis(0, NUM_KEYS - 1);
while (!stop.load()) {
int key = dis(gen);
int value = key * 1000 + t; // 带线程 ID 的值,便于追踪
cache.put(key, value);
// 小延迟避免过度占用 CPU(可选)
// std::this_thread::sleep_for(std::chrono::microseconds(1));
}
});
}
// === 读线程:不断 get 并校验 ===
std::atomic<long> read_count{0};
std::atomic<long> error_count{0};
for (int t = 0; t < NUM_READERS; ++t) {
threads.emplace_back([&cache, &stop, &read_count, &error_count, t, NUM_KEYS]() {
std::mt19937 gen(t + 1000);
std::uniform_int_distribution<> dis(0, NUM_KEYS - 1);
while (!stop.load()) {
int key = dis(gen);
int value;
if (cache.get(key, value)) {
// 校验:value 应为 key * 1000 + writer_id
// 由于多个 writer 可能写同一 key,只要满足 value % 1000 == key 即可
if (value / 1000 != key) {
++error_count;
std::cerr << "Invalid value for key=" << key
<< ", got=" << value << "\n";
}
}
++read_count;
}
});
}
// 运行指定时间
std::this_thread::sleep_for(std::chrono::seconds(DURATION_SEC));
stop.store(true);
// 等待所有线程结束
for (auto& th : threads) {
th.join();
}
// === 最终一致性检查 ===
std::cout << "Test finished.\n";
std::cout << "Total reads: " << read_count.load() << "\n";
std::cout << "Errors: " << error_count.load() << "\n";
std::cout << "Final cache size: " << cache.size() << " (capacity=" << CAPACITY << ")\n";
// 断言:缓存大小不能超过容量
assert(cache.size() <= CAPACITY && "Cache size exceeds capacity!");
// 断言:无逻辑错误
assert(error_count.load() == 0 && "Data inconsistency detected!");
std::cout << "✅ All tests passed!\n";
}
// 主函数
int main() {
try {
run_multithread_test();
} catch (const std::exception& e) {
std::cerr << "Test failed with exception: " << e.what() << "\n";
return 1;
}
return 0;
}