基本
QgsConnectionPool是一个负责维持开放连接的模板类,用于避免每次创建新连接时的开销。接口都是线程安全的。
template <typename T, typename T_Group>
class QgsConnectionPool
{
public:
typedef QMap<QString, T_Group *> T_Groups;
T一般表示连接类,T_Group表示连接的集合。在QgConnectionPool内部通过成员变量protected: T_Groups mGroups;
管理连接,T_Groups为:typedef QMap<QString, T_Group *> T_Groups
。
acquireConnection()
T acquireConnection( const QString &connInfo, int timeout = -1, bool requestMayBeNested = false, QgsFeedback *feedback = nullptr )
acquireConnection()用于获取一个连接。
mMutex.lock();
typename T_Groups::iterator it = mGroups.find( connInfo );
if ( it == mGroups.end() )
{
it = mGroups.insert( connInfo, new T_Group( connInfo ) );
}
T_Group *group = *it;
mMutex.unlock();
首先从Map中根据连接信息查找到连接集合,如果没有,则新建并插入到map中。
if ( feedback )
{
QElapsedTimer timer;
timer.start();
while ( !feedback->isCanceled() )
{
if ( T conn = group->acquire( 300, requestMayBeNested ) )
return conn;
if ( timeout > 0 && timer.elapsed() >= timeout )
return nullptr;
}
return nullptr;
}
feedback
用于在获得连接前取消该请求。如果传入了feedback,则开始计时并一直尝试获取,直到被取消或超时。
else
{
return group->acquire( timeout, requestMayBeNested );
}
如果没有feedback,则直接调用T_Group的acquire()
接口获取连接。关于T_Group如何获取连接的可参考QgsConnectionPoolGroup类分析
releaseConnection()
void releaseConnection( T conn )
releaseConnection()用于将使用完的连接放回连接池中。
mMutex.lock();
typename T_Groups::iterator it = mGroups.find( qgsConnectionPool_ConnectionToName( conn ) );
Q_ASSERT( it != mGroups.end() );
T_Group *group = *it;
mMutex.unlock();
group->release( conn );
releaseConnection()的实现很简单,根据conn获得连接信息,并从连接map中查找,之后调用T_Group的release()
接口减少一个引用。
网友评论