Time controlled user-input
user has 5 secs to enter his/her full name from console, else this option is withdrawn and the name entry process becomes different:
i'm using std::future with std::launch::async and a wait.until(5secs) before checking if std::future::status::ready in which case I call get() on the future, or else we go into the alternative name entry process
problem is that if user doesn't enter name within 5 secs the thread still continues in the background and the rest of the program becomes undefined. How can I kill this thread there and then once 5 secs are up?
Code:
#include <iostream>
#include <string>
#include <future>
#include <chrono>
int main()
{
std::string name{};
auto tp = std::chrono::system_clock::now() + std::chrono::seconds(5);
std::future<void> f =
std::async(std::launch::async, [&name]()
{
std::cout << "enter your name \n"; getline(std::cin, name);
std::cout << "well in time, your name is: " << name << "\n";
});
std::future_status s = f.wait_until(tp);
if (s == std::future_status::ready)
{
f.get();
}
else
{
std::cout << "took too long, enter first name now \n";
std::string first_name{};
getline(std::cin, first_name);
std::cout << "now enter last name \n";
std::string last_name{};
std::cout << "full name is: " << first_name << " " << last_name << "\n";
}
}
my early forays into concurrency so if I'm doing something(s) else very wrong please do not hesitate to let me know. Many thanks
edit: apologies for the formatting, something went awry between my text-editor and this page