I want to make a keyboard interrupt to exit a while loop. Instead of using _getchar() or cin inside the while loop, which wait for the user input, I want to find a way that allows for an optional keyboard interrupt: the loop should continue indefinitely until the user decides to stop it.
For this goal, creating threads could help, but I am very new into the topic. I implemented this in this example code. I use C++ Visual Studio 2019 in Windows.
#include <iostream> // std::cout
#include <thread> // std::thread
int exitWhile = 0;
void interrupt()
{
std::cin >> exitWhile; // Get "exitWhile" from keyboard
}
int main()
{
std::thread t(interrupt); // Spawn new thread
while (exitWhile != 1) // If keyboard input is "1", exit while loop
{
std::cout << "Inside while loop" << std::endl;
t.join();
}
std::cout << "Exit while.\n";
return 0;
}
However, the while loop is executed one first time and then waits for the thread "t" to be finished because of the join() function. I would like to run the thread in parallel such that the global variable gets modified at any time, until which the while loop will keep repeating. Any ideas on how to implement this behavior?