Question Details

No question body available.

Tags

c++ multithreading io iostream

Answers (2)

September 18, 2025 Score: 2 Rep: 75,125 Quality: Low Completeness: 70%

Your current approach may work quite fine with normal files, as these getline() would return in a relatively predictable time and each occurence of the loop is an opportunity to leave it. The only issue is that you don't check if the read was successful or if we're aleady at the end fo the file.

If getline() ought to read from an input device like cin, you cannot prevent the function from being blocked waiting for input in absence of any fatal error. The approach is then to read the input only if we're sure there is some input to read.

Unfortunately, there is no universal and portable way to deal with such situations. The simplest approach could just be to check for available input as explained in this SO answer or here. If no input is available, you'd just loop once more giving the opportunity of stopping the thread.

September 17, 2025 Score: -3 Rep: 478 Quality: Low Completeness: 50%

well getline on wcin is blocking and can not be interrupted just by setting a flag or closing the socket. That why your thread never exits, i used C++ back in uni, but as far i know the simple way is to just detach the thread instead of trying to join it. this should work fine.

thread inputThread([&]{
    while (true) {
        wstring message;
        if (!getline(wcin, message)) break
        if (!message.empty()) {
            send(sock, message.data(), (message.size()+1) * sizeof(wchar_t), 0);
        }
    }
});

running = false; close(sock); inputThread.detach(); // don't wait on getline