I have an application that reads data from standard input using getline () in a stream. I want to close the application from the main thread, while getline is still blocking another thread. How can this be achieved?
I do not want users to press ctrl-Z to close stdin and the application.
I already tried with the settings of my compiler (RuntimeLibrary = / MT) on Windows 8.1 64bit, v120 platform toolet:
- freopen stdin, but it is locked by an internal lock
- breaking the thread calling abort ()
- putback a Eof, end of line in std :: cin, which also blocked
* Update *
- detach () does not work, exit () is locked by a lock
- winapi TerminatThread () causes interrupt ()
- winapi CloseHandle (GetStdHandle (STD_INPUT_HANDLE)) freezes
- calling TerminateProcess () - works, but I would like to exit gracefully
* Update 2: Solution *
- WriteConsoleInput () can convert std :: getline () from a read lock. This works with any msvc runtime libray. For a working solution code, see Accepted Answer.
Sample code showing the problem:
#include <iostream> #include <thread> #include <string> #include <chrono> int main(int argc, char *argv[]) { bool stop = false; std::thread *t = new std::thread([&]{ std::string line; while (!stop && std::getline(std::cin, line, '\n')) { std::cout << line; } }); std::this_thread::sleep_for(std::chrono::seconds(1)); stop = true; // how to stop thread or make getline to return here? return 0; }
simon source share