1 /* 2 * This file is part of PowerDNS or dnsdist. 3 * Copyright -- PowerDNS.COM B.V. and its contributors 4 * 5 * This program is free software; you can redistribute it and/or modify 6 * it under the terms of version 2 of the GNU General Public License as 7 * published by the Free Software Foundation. 8 * 9 * In addition, for the avoidance of any doubt, permission is granted to 10 * link this program with OpenSSL and to (re)distribute the binaries 11 * produced as the result of such linking. 12 * 13 * This program is distributed in the hope that it will be useful, 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 * GNU General Public License for more details. 17 * 18 * You should have received a copy of the GNU General Public License 19 * along with this program; if not, write to the Free Software 20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 */ 22 #pragma once 23 24 #include <mutex> 25 26 class ConcurrentConnectionManager 27 { 28 public: ConcurrentConnectionManager(size_t max)29 ConcurrentConnectionManager(size_t max): d_maxConcurrentConnections(max) 30 { 31 } 32 setMaxConcurrentConnections(size_t max)33 void setMaxConcurrentConnections(size_t max) 34 { 35 std::lock_guard<decltype(d_concurrentConnectionsLock)> lock(d_concurrentConnectionsLock); 36 d_maxConcurrentConnections = max; 37 } 38 registerConnection()39 bool registerConnection() 40 { 41 std::lock_guard<decltype(d_concurrentConnectionsLock)> lock(d_concurrentConnectionsLock); 42 if (d_maxConcurrentConnections == 0 || d_currentConnectionsCount < d_maxConcurrentConnections) { 43 ++d_currentConnectionsCount; 44 return true; 45 } 46 return false; 47 } 48 releaseConnection()49 void releaseConnection() 50 { 51 std::lock_guard<decltype(d_concurrentConnectionsLock)> lock(d_concurrentConnectionsLock); 52 --d_currentConnectionsCount; 53 } 54 55 private: 56 std::mutex d_concurrentConnectionsLock; 57 size_t d_maxConcurrentConnections{0}; 58 size_t d_currentConnectionsCount{0}; 59 }; 60