In my application, I have a thread which just runs std::getline() constantly to get user input, to then send it to a server via a socket. I've made a signal handler to close the program properly when I receive SIGINT. The signal calls a function named stop(), which closes the socket, and then I try to join my input thread. I have a problem stopping this thread, which I don't know how to solve.
atomic<bool> running = true;
int sock; //socket descriptor
void stop() {
running = false;
close(sock);
}
wstring message = L"";
thread inputThread = thread([&]{
while(running) {
getline(wcin, message, L'\n');
if (message.size() > 0) {
send(sock, reinterpret_cast<const void*>(message.data()), (message.size()+1) * sizeof(wchar_t), 0);
}
}
});
The problem is that getline() blocks the thread even when running is false, preventing the thread from joining properly. send() does not block it, because the socket is already closed by that time. How do I close this thread, or how do I interrupt getline()?
I've tried using close(STDIN_FILENO); in the stop() function, but this seemed to not help, it does not end the thread.
std::jthreadand you won't need aatomic<bool> running = true;or astop()function, and you can stop the thread by simply destroying it.send()though.std::getline(). Either your user needs to provide input that causes the loop to terminate, or you need to use some platform-specific means of asynchronous input and means of interrupting it.