From 5326102801eac81bec9e63e3e0fc6662150c03a8 Mon Sep 17 00:00:00 2001 From: Sascha Kuehl Date: Mon, 27 Nov 2023 17:38:22 +0100 Subject: [PATCH] enhanced connection pool to acquire connection by specific id --- include/matador/sql/connection_pool.hpp | 29 +++++++++++++++++-------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/include/matador/sql/connection_pool.hpp b/include/matador/sql/connection_pool.hpp index 3e7b6f4..0a7091a 100644 --- a/include/matador/sql/connection_pool.hpp +++ b/include/matador/sql/connection_pool.hpp @@ -1,12 +1,11 @@ #ifndef QUERY_CONNECTION_POOL_HPP #define QUERY_CONNECTION_POOL_HPP -#include -#include +#include #include #include +#include #include -#include namespace matador::sql { @@ -81,7 +80,6 @@ public: return {nullptr, *this}; } - pointer next_connection{nullptr}; for (auto &item : idle_connections_) { next_connection = item.second; @@ -93,8 +91,24 @@ public: } connection_ptr acquire(size_t id) { - std::lock_guard guard(mutex_); - return {nullptr, *this}; + using namespace std::chrono_literals; + pointer next_connection{nullptr}; + auto try_count{0}; + std::unique_lock lock(mutex_); + + do { + if (auto it = idle_connections_.find(id); it != idle_connections_.end()) { + next_connection = it->second.second; + auto node = idle_connections_.extract(it); + inuse_connections_.insert(std::move(node)); + } else { + lock.unlock(); + std::this_thread::sleep_for(500ms); + lock.lock(); + } + } while(try_count++ < 5); + + return {next_connection, *this}; } void release(IdConnection *c) { @@ -130,10 +144,7 @@ private: mutable std::mutex mutex_; std::vector> connection_repo_; using pointer = IdConnection*; - using connections = std::queue; using connection_map = std::unordered_map; - using connection_set = std::unordered_set; -// connections idle_connections_; connection_map inuse_connections_; connection_map idle_connections_;