-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlockfree_object_pool_test.cpp
More file actions
50 lines (42 loc) · 1.18 KB
/
lockfree_object_pool_test.cpp
File metadata and controls
50 lines (42 loc) · 1.18 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
#include "lockfree_object_pool.h"
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
struct Packet {
int id;
char data[64];
static std::atomic<int> counter;
Packet() : id(++counter) {
// std::cout << "Packet #" << id << " created\n";
}
~Packet() {
// std::cout << "Packet #" << id << " destroyed\n";
}
};
std::atomic<int> Packet::counter{0};
void reset_packet(Packet& p) {
// 清理业务数据
}
int main() {
LockFreeObjectPool<Packet>::Config cfg;
cfg.max_cached = 1000;
cfg.resetter = reset_packet;
LockFreeObjectPool<Packet> pool(cfg);
const int num_threads = 4;
const int ops_per_thread = 100000;
std::vector<std::thread> threads;
for (int i = 0; i < num_threads; ++i) {
threads.emplace_back([&pool, ops_per_thread]() {
for (int j = 0; j < ops_per_thread; ++j) {
auto p = pool.acquire();
// 模拟使用
p->data[0] = 'A';
pool.release(std::move(p));
}
});
}
for (auto& t : threads) t.join();
std::cout << "Final cached: " << pool.cached_size() << "\n";
return 0;
}