概述
在使用 Java 时,Apache Common Pool 是一个非常常用的通用池解决方案,使用池技术可以缓存较为常用的对象、数据库连接、文件句柄等,避免在每次使用时创建,提高应用程序的响应速度。
对于一个通用池,应当提供以下功能:
- 可配置的初始化池大小、最大池大小、最多空闲资源大小;
- 提供获取资源、归还资源的 API;
- 在资源不足时能够使当前线程阻塞以等待资源被归还.
本文使用 C++ 模板技术编写一个通用的池。
设计
首先,应当有三个属性分别保存初始化池大小、最大池大小、最多空闲资源大小。
对于一个通用池,应当存在一个容器存放空闲的资源,一个容器存放正在使用的资源。为使池中的各个资源被平均地被使用,这里使用一个 std::list
作为一个队列,每次在获取资源时从队列头获取一个资源。
正在使用的资源不需要保持有序,这里使用 std::unordered_set
存放。
对于阻塞线程的需求,使用 std::metux
与 std::condition_variable
来实现。
另外,为方便使用通用池,使用 RAII 机制,提供一个释放池的 CommonPoolReleaseGuard
,能够在变量退出作用域时自动归还资源。
代码
这里直接贴代码
|
|
如何使用
首先对于资源的生成,通用池提供了一个模板参数 Builder
,在使用时需要编写一个 Builder
类,这里以 MySQL 连接 mysql-connector-cpp 为例。
|
|
此处,建立了 MysqlPool
类,继承了 CommonPool
,这里管理的资源是 sql::Connection
。
实际使用时,利用 CommonPoolReleaseGuard
较为方便的释放资源 :
|
|