I have a simple c++ thread that waits for user to prematurely kill the program by pressing 'q' then runs the kill sequence. My problem is, the user does not always press 'q' and usually the programs runs its course.
However I cannot find a good way to end the thread in cases where user does not press "q". I've been just returning from main with the thread open and letting the program crash. While this works, I am hoping there is a more elegant solution out there. I've also tried to detach the thread before returning from main, and while this does not cause a crash, It's behavior is undefined. Some say the thread will run indefinitely.
void manualKill(killEventClass &killEvent)
{
cin.ignore(1000, 'q');
killEvent.set();
}
int main()
{
thread manualKillThread(manualKill, ref(killEventClass));
//do stuff
manualKillThread.detach();
return 0;
}
Edit:
It appears that there is no way to do this with the standard C++ library, I would have to find some OS specific approach that captures keys.
Honestly detaching the thread, while it's not ideal, it is portable, and probably the lesser evil. Since my program is ending regardless.
Thank you for all your answers.