From 642c1c80fa0d321e5a8ab8e26fac85403ec8146f Mon Sep 17 00:00:00 2001 From: neru Date: Sat, 11 Apr 2026 12:21:59 -0300 Subject: [PATCH] feat: add thread pools --- src/unlocker/proxy.cpp | 33 ++++++++++++++++++++++++++++++++- src/unlocker/proxy.h | 9 +++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/unlocker/proxy.cpp b/src/unlocker/proxy.cpp index a5a828b..fee0f76 100644 --- a/src/unlocker/proxy.cpp +++ b/src/unlocker/proxy.cpp @@ -205,6 +205,24 @@ bool Proxy::init() listen(_listenSocket, SOMAXCONN); _running = true; + for (int i = 0; i < 16; ++i) + { + _poolThreads.emplace_back([this]() { + while (_running) + { + SOCKET client; + { + std::unique_lock lock(_queueMutex); + _queueCond.wait(lock, [this]() { return !_clientQueue.empty() || !_running; }); + if (!_running && _clientQueue.empty()) return; + client = _clientQueue.front(); + _clientQueue.pop(); + } + this->handleClient(client); + } + }); + } + _workerThread = std::thread(&Proxy::loop, this); Log::verbose("Proxy active on 127.0.0.1:{}", PROXY_PORT); @@ -222,6 +240,14 @@ void Proxy::shutdown() _listenSocket = INVALID_SOCKET; } if (_workerThread.joinable()) _workerThread.join(); + + _queueCond.notify_all(); + for (auto& t : _poolThreads) + { + if (t.joinable()) t.join(); + } + _poolThreads.clear(); + WSACleanup(); cleanupSSL(); } @@ -237,7 +263,12 @@ void Proxy::loop() break; } if (client == INVALID_SOCKET) continue; - std::thread([this, client]() { this->handleClient(client); }).detach(); + + { + std::lock_guard lock(_queueMutex); + _clientQueue.push(client); + } + _queueCond.notify_one(); } } diff --git a/src/unlocker/proxy.h b/src/unlocker/proxy.h index 6332c83..77c10bb 100644 --- a/src/unlocker/proxy.h +++ b/src/unlocker/proxy.h @@ -3,6 +3,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include "ssl.h" @@ -39,6 +43,11 @@ class Proxy std::thread _workerThread; std::atomic _running = false; + std::vector _poolThreads; + std::queue _clientQueue; + std::mutex _queueMutex; + std::condition_variable _queueCond; + CertManager _certManager; SSL_CTX* _clientCtx = nullptr; };