diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index c1a8cff2..5f070d33 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,10 @@ All changes to this project will be documented in this file. +## [10.2.3] - 2020-08-15 + +(socket server) instead of busy looping with a sleep, only wake up the GC thread when a new thread will have to be joined, (we know that thanks to the ConnectionState OnSetTerminated callback + ## [10.2.2] - 2020-08-15 (socket server) add a callback to the ConnectionState to be invoked when the connection is terminated. This will be used by the SocketServer in the future to know on time that the associated connection thread can be terminated. diff --git a/ixwebsocket/IXSocketServer.cpp b/ixwebsocket/IXSocketServer.cpp index f0779071..c57acf05 100644 --- a/ixwebsocket/IXSocketServer.cpp +++ b/ixwebsocket/IXSocketServer.cpp @@ -204,6 +204,7 @@ namespace ix if (_gcThread.joinable()) { _stopGc = true; + _conditionVariableGC.notify_one(); _gcThread.join(); _stopGc = false; } @@ -259,7 +260,7 @@ namespace ix if (_stop) return; // Use poll to check whether a new connection is in progress - int timeoutMs = 10000; + int timeoutMs = 10; bool readyToRead = true; PollResultType pollResult = Socket::poll(readyToRead, timeoutMs, _serverFd, _acceptSelectInterrupt); @@ -415,8 +416,14 @@ namespace ix break; } - // Sleep a little bit then keep cleaning up - std::this_thread::sleep_for(std::chrono::milliseconds(10)); + // Unless we are stopping the server, wait for a connection + // to be terminated to run the threads GC, instead of busy waiting + // with a sleep + if (!_stopGc) + { + std::unique_lock lock(_conditionVariableMutexGC); + _conditionVariableGC.wait(lock); + } } } @@ -427,6 +434,8 @@ namespace ix void SocketServer::onSetTerminatedCallback() { - ; + // a connection got terminated, we can run the connection thread GC, + // so wake up the thread responsible for that + _conditionVariableGC.notify_one(); } } // namespace ix diff --git a/ixwebsocket/IXSocketServer.h b/ixwebsocket/IXSocketServer.h index c9c286cc..caf00ee5 100644 --- a/ixwebsocket/IXSocketServer.h +++ b/ixwebsocket/IXSocketServer.h @@ -117,5 +117,10 @@ namespace ix // to wake up from select SelectInterruptPtr _acceptSelectInterrupt; + + // used by the gc thread, to know that a thread needs to be garbage collected + // as a connection + std::condition_variable _conditionVariableGC; + std::mutex _conditionVariableMutexGC; }; } // namespace ix