I have an application, which reads data from standard input using getline() in a thread. I want to close the application from the main thread, while getline still block the other thread. How can this be achieved?
I have tried so far:
- freopen stdin, but it is blocked by internal lock
- destructing the thread, which calls abort()
- putback an Eof, line end to std::cin, which also blocked
I don't want to force the users to have to press ctrl-Z to close stdin and the application.
Example code:
#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;
}
Aucun commentaire:
Enregistrer un commentaire