-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_safe_object_pool.cpp
More file actions
68 lines (57 loc) · 1.96 KB
/
thread_safe_object_pool.cpp
File metadata and controls
68 lines (57 loc) · 1.96 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
#include "thread_safe_object_pool.h"
// === 示例对象 ===
struct WorkItem {
int id = 0;
std::string payload;
WorkItem() {
// 确保多线程下id唯一
static std::atomic<int> counter{0};
id = ++counter;
std::cout << "WorkItem #" << id << " created\n";
}
~WorkItem() {
std::cout << "WorkItem #" << id << " destroyed\n";
}
};
void reset_work_item(WorkItem& item) {
item.payload.clear();
std::cout << "WorkItem #" << item.id << " reset\n"; // 可选日志
}
// === 主函数:多线程测试 ===
int main() {
// 配置池
using Pool = ThreadSafeObjectPool<WorkItem>;
Pool::Config cfg;
cfg.max_cached = 3;
cfg.resetter = reset_work_item;
Pool pool(cfg);
// 启动4个线程,每个获取5个对象
const int num_threads = 4;
const int items_per_thread = 5;
std::vector<std::thread> threads;
for (int tid = 0; tid < num_threads; ++tid) {
// emplace_back( lambda ), 启动一个线程,运行这个lambda函数,并把改线程对象加入到threads数组中
threads.emplace_back([&, tid]() {
std::vector<std::unique_ptr<WorkItem>> local_items;
for (int i = 0; i < items_per_thread; ++i) {
auto item = pool.acquire();
if (item) {
item->payload = "Thread" + std::to_string(tid) + "-Job" + std::to_string(i);
// 模拟工作
std::this_thread::sleep_for(std::chrono::milliseconds(10));
local_items.push_back(std::move(item)); // 暂存,稍后归还
}
}
// 归还所有对象
for (auto& item : local_items) {
pool.release(std::move(item));
}
});
}
// 等待所有线程结束
for (auto& t : threads) {
t.join();
}
std::cout << "\nFinal cached objects in pool: " << pool.cached_size() << "\n";
return 0;
}