Network System 0.1.1
High-performance modular networking library for scalable client-server applications
Loading...
Searching...
No Matches
connection_pool.h
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2024, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
5#pragma once
6
7#include <atomic>
8#include <chrono>
9#include <condition_variable>
10#include <memory>
11#include <mutex>
12#include <queue>
13#include <string>
14
17
19{
20
55 class connection_pool
56 {
57 public:
68 std::string host, unsigned short port, size_t pool_size = 10,
69 std::chrono::seconds acquire_timeout = std::chrono::seconds(30));
70
74 ~connection_pool() noexcept;
75
83 auto initialize() -> VoidResult;
84
93 auto acquire() -> std::unique_ptr<messaging_client>;
94
102 auto release(std::unique_ptr<messaging_client> client) -> void;
103
108 [[nodiscard]] auto active_count() const noexcept -> size_t
109 {
110 return active_count_.load(std::memory_order_relaxed);
111 }
112
117 [[nodiscard]] auto pool_size() const noexcept -> size_t
118 {
119 return pool_size_;
120 }
121
122 private:
123 std::string host_;
124 unsigned short port_;
125 size_t pool_size_;
126 std::chrono::seconds acquire_timeout_;
129 std::queue<std::unique_ptr<messaging_client>> available_;
131 std::atomic<size_t> active_count_{0};
133 std::mutex mutex_;
134 std::condition_variable cv_;
135 std::atomic<bool> is_shutdown_{false};
137 };
138
139} // namespace kcenon::network::core
~connection_pool() noexcept
Destructor. Stops all connections and cleans up resources.
connection_pool(std::string host, unsigned short port, size_t pool_size=10, std::chrono::seconds acquire_timeout=std::chrono::seconds(30))
Constructs a connection pool.
auto acquire() -> std::unique_ptr< messaging_client >
Acquires a connection from the pool.
auto pool_size() const noexcept -> size_t
Gets the total pool size.
std::queue< std::unique_ptr< messaging_client > > available_
auto initialize() -> VoidResult
Initializes the pool by creating and connecting all clients.
auto release(std::unique_ptr< messaging_client > client) -> void
Releases a connection back to the pool.
auto active_count() const noexcept -> size_t
Gets the number of active (borrowed) connections.
TCP client implementation.
Result< std::monostate > VoidResult
Network-specific error and result type definitions.