enhanced connection pool to acquire connection by specific id

This commit is contained in:
Sascha Kuehl 2023-11-27 17:38:22 +01:00
parent 93b868aaaf
commit 5326102801
1 changed files with 20 additions and 9 deletions

View File

@ -1,12 +1,11 @@
#ifndef QUERY_CONNECTION_POOL_HPP
#define QUERY_CONNECTION_POOL_HPP
#include <utility>
#include <queue>
#include <chrono>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
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<Connection> acquire(size_t id) {
std::lock_guard<std::mutex> guard(mutex_);
return {nullptr, *this};
using namespace std::chrono_literals;
pointer next_connection{nullptr};
auto try_count{0};
std::unique_lock<std::mutex> 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<Connection> *c) {
@ -130,10 +144,7 @@ private:
mutable std::mutex mutex_;
std::vector<IdConnection<Connection>> connection_repo_;
using pointer = IdConnection<Connection>*;
using connections = std::queue<pointer>;
using connection_map = std::unordered_map<size_t, pointer>;
using connection_set = std::unordered_set<pointer>;
// connections idle_connections_;
connection_map inuse_connections_;
connection_map idle_connections_;