The problem I am facing is that the application does not exit when I type "exit" in the console. It gets stuck in the follwing thread:
void server<T>::handleClientConnections(int serverSocketFD, std::atomic<bool> &__flag)
{
std::vector<std::thread> __threads;
while (__flag.load())
{
acceptedSocket newAcceptedSocket;
if (!acceptConnection(serverSocketFD, newAcceptedSocket))
continue;
connectedSockets.push_back(newAcceptedSocket);
std::thread thread(&server::receivedDataHandlerThread, this, newAcceptedSocket);
thread.detach();
__threads.push_back(std::move(thread));
}
for (auto &thread : __threads)
thread.join();
for (const auto &socket : connectedSockets)
close(socket.getAcceptedSocketFD());
}
I am creating a thread for each connection and I am using an atomic variable to signal the other threads. (SERVER_RUNNING is declared as a global std::atomic)
template <typename T>
void server<T>::consoleListener(std::atomic<bool> &__flag)
{
underline(75);
char input[101] = "";
while (__flag.load())
{
std::cout << std::setw(5) << " "
<< "--> ";
std::cin >> input;
if (strcasecmp(input, "exit") == 0)
{
std::cout << std::setw(5) << " "
<< "Shutting down...\n";
__flag.store(false);
break;
}
}
}
template <typename T>
void server<T>::server_easy_init(int serverSocketFD)
{
SERVER_RUNNING.store(true);
std::thread workerThread(&server::handleClientConnections, this, serverSocketFD, std::ref(SERVER_RUNNING));
consoleListener(std::ref(SERVER_RUNNING));
workerThread.join();
}
Thank you!
I tried using a mutex and the condition variable, but I encountered the same bug.
This is what the updated code:
But now I get a couple memory leaks :)
Anyways, thanks a lot for the help!