0

I need to run some iterative algorithm of which I don't know whether it will converge to the desired accuracy within reasonable time. It would therefore be cool if I could print the residual after each iteration and once I'm satisfied/out of patience I could tell the program to write the current solution to disk and terminate.

Usually, to achieve this the program would have to ask after every iteration whether it should terminate now, and most of the time I would have to tell it not to. This is clearly annoying. Can't I tell the program to run until I hit a certain key, and once I do it should finish the current iteration, write the approximation to disk and terminate?

1 Answer 1

4

Yes, you can, and you can even do it using only standard C++11 features. The trick is to spawn a new thread whose only job it is to listen to std::cin. Once the user writes anything, the listening thread sets a flag which tells the worker thread to abort. In the following small example, I implement a "stopwatch" using this technique.

#include <iostream> #include <thread> #include <atomic> int main() { std::atomic<bool> abort(false); std::thread t([&abort] () { std::cout << "Abort?"; std::cin.peek(); abort = true; }); unsigned long i = 0; while (!abort) ++i; t.join(); std::cout << "Counted to " << i << std::endl; return 0; } 

You may now try to terminate the program exactly when it reached 100000000. :-)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.