c++ - Asynchronous IO in C++11 -
i need run iterative algorithm of don't know whether converge desired accuracy within reasonable time. hence cool if print residual after each iteration , 1 time i'm satisfied/out of patience tell programme write current solution disk , terminate.
usually, accomplish programme have inquire after every iteration whether should terminate now, , of time have tell not to. annoying. can't tell programme run until nail key, , 1 time should finish current iteration, write approximation disk , terminate?
yes, can, , can using standard c++11 features. trick spawn new thread job hear std::cin
. 1 time user writes anything, listening thread sets flag tells worker thread abort. in next little example, implement "stopwatch" using 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 = 0; while (!abort) ++i; t.join(); std::cout << "counted " << << std::endl; homecoming 0; }
you may seek terminate programme when reached 100000000. :-)
c++ multithreading c++11 atomic
No comments:
Post a Comment