diff --git a/CommonConnectionPool.h b/CommonConnectionPool.h index 5d1bc73..f64ae84 100644 --- a/CommonConnectionPool.h +++ b/CommonConnectionPool.h @@ -18,6 +18,7 @@ class Connectionpool shared_ptr getConnection();//给外部提供接口,从连接池获取一个可用的空闲连接 private: Connectionpool();//单例1 + ~Connectionpool(); bool loadConfigFile();//从配置文件中加载配置项 //运行在独立的线程中,专门负责产生新连接 @@ -38,4 +39,7 @@ class Connectionpool mutex _queueMutex;//维护连接队列的线程安全互斥锁 atomic_int _connectionCnt;//记录所创建的connection连接的总数量 condition_variable cv;// + + std::atomic_bool _stop; + std::counting_semaphore<1> _sem{0}; }; \ No newline at end of file diff --git a/CommonConnectionpool.cpp b/CommonConnectionpool.cpp index 076e2f1..e1b8b7c 100644 --- a/CommonConnectionpool.cpp +++ b/CommonConnectionpool.cpp @@ -74,7 +74,7 @@ bool Connectionpool::loadConfigFile() return true; } -Connectionpool::Connectionpool() +Connectionpool::Connectionpool:_stop(false)() { if (!loadConfigFile()) @@ -103,11 +103,11 @@ void Connectionpool::produceConnectionTask() for (;;) { unique_lock lock(_queueMutex); - while (!_connectionQue.empty()) + while (!_connectionQue.empty()&&!_stop) { cv.wait(lock); // } - + if(_stop){break;} if (_connectionCnt < _maxSize) { @@ -176,5 +176,21 @@ void Connectionpool::scannerConnectionTask() break; // 队头的连接没有超过_maxIdleTime,其他连接肯定没有 } } + + if(_stop) { + while(!_connectionQue.empty()) { + Connection *p = _connectionQue.front(); + _connectionQue.pop(); + delete p; + } + _sem.release(); + break; + } } -} \ No newline at end of file +} + +ConnectionPool::~ConnectionPool() { + _stop = true; + cv.notify_all(); // 模拟一下消费者,唤醒生产者 + _sem.acquire(); +}