Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

cpp-pool — C++17 资源池集合

三个独立可用的高性能资源池组件:数据库连接池内存池线程池。支持泛型,线程安全,零外部依赖(仅 pthread)。


组件概览

组件 文件 用途
数据库连接池 Database_connection_pool.cpp 泛型连接池:RAII 借用、健康检查、后台回收、超时
内存池 Memory_Pool.cpp FixedSizeMemoryPool + SlabAllocator + TLS 批量缓存
线程池 Thread_Pool.cpp 弹性线程池:暂停/恢复、WaitAll、动态扩缩、异常隔离

一、数据库连接池

基于 ConnectionFactory<Conn> 的泛型设计,适配任意数据库后端。

特性:

  • 预热 min_size 个连接
  • RAII Borrowed 句柄 — 析构自动归还
  • 健康检查 — 借出前 ping 验证
  • 后台回收 — 空闲超时连接自动销毁(保留 min_size)
  • 获取超时 — wait_ms 后抛异常而非无限等待
  • 线程安全 — mutex + condition_variable

核心 API:

auto pool = std::make_shared<ConnectionPool<FakeSQLite>>(...);
auto conn = pool->Get();      // 返回 RAII Borrowed 句柄
conn->Exec("SELECT ...");     // 使用连接
// 析构自动归还

用法:

g++ -std=c++17 -pthread -O2 Database_connection_pool.cpp -o db_pool && ./db_pool

二、内存池

FixedSizeMemoryPool

单尺寸、无锁内存池。基于 Treiber Stack,块大小自动对齐。

FixedSizeMemoryPool pool(sizeof(MyStruct), 256);
auto* obj = static_cast<MyStruct*>(pool.Allocate());
// ... 使用 obj
pool.Deallocate(obj);

SlabAllocator

多尺寸分配器 — 8 个尺寸档(16B → 4KB)。请求向上取整到最近的档位,每档独立无锁栈。

SlabAllocator slab;
void* p = slab.Allocate(120);   // → 归入 128B slab
slab.Deallocate(p, 120);

TlsCache(TLS 批量缓存)

线程局部预取/延迟归还 — 批量接送连接,减少 CAS 竞争。

TlsCache cache(alloc_fn, free_fn);
void* p = cache.Get();   // 从本地缓存取,空则批量拉取
cache.Put(p);            // 归还本地缓存,满则批量冲刷

用法:

g++ -std=c++17 -pthread -O2 Memory_Pool.cpp -o memory_pool && ./memory_pool

三、线程池

弹性线程池,支持动态管理任务队列。

特性:

  • 可变大小 — 可运行时 Resize(n)
  • Pause() / Resume() — 暂停/恢复任务处理
  • WaitAll() — 等待所有排队和运行中的任务完成
  • 完美转发 — Enqueue(f, args...) 返回 std::future<Ret>
  • 异常隔离 — worker 中未捕获异常不导致线程退出
  • 统计 — Active() / Queued() / Completed()

核心 API:

ThreadPool pool(4);
auto fut = pool.Enqueue([i]() { return i * i; });
int result = fut.get();                  // 取得结果
pool.WaitAll();                          // 等待全部完成
pool.Pause();  pool.Resume();            // 暂停/恢复
pool.Resize(8);                          // 扩容

用法:

g++ -std=c++17 -pthread -O2 Thread_Pool.cpp -o thread_pool && ./thread_pool

构建(CMake)

cmake -B build -S .
cmake --build build
./build/memory_pool
./build/thread_pool
./build/db_pool

依赖

  • C++17(GCC 9+ / Clang 10+)
  • pthread
  • 无第三方库依赖

About

cpp-pool 是一个 C++17 资源池三件套:泛型数据库连接池(RAII 借用 + 健康检查)、内存池(无锁栈 + Slab 多尺寸 + TLS 缓存)、弹性线程池(暂停/恢复/WaitAll)。均单文件、零外部依赖、仅需 pthread。

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages