c++ - How to stop a async evaluating function on timeout? -
say have simple async call want kill/terminate/eliminate on timeout
// future::wait_for #include <iostream> // std::cout #include <future> // std::async, std::future #include <chrono> // std::chrono::milliseconds // non-optimized way of checking prime numbers: bool is_prime (int x) { (int i=2; i<x; ++i) if (x%i==0) return false; return true; } int main () { // call function asynchronously: std::future<bool> fut = std::async (is_prime,700020007); // while waiting function set future: std::cout << "checking, please wait"; std::chrono::milliseconds span (100); while (fut.wait_for(span)==std::future_status::timeout) std::cout << '.'; bool x = fut.get(); std::cout << "\n700020007 " << (x?"is":"is not") << " prime.\n"; return 0; }
we want kill first timeout happens. cant find method in future.
the closest find stop running task std::packaged_task
reset
method yet not if can interrupt running task. how 1 kills task running asyncrinusly not using boost thread or other non stl libraries?
it's not possible stop std::async
out of box... however, can this, pass bool
terminate is_prime
method , throw exception if there timeout:
// future::wait_for #include <iostream> // std::cout #include <future> // std::async, std::future #include <chrono> // std::chrono::milliseconds // non-optimized way of checking prime numbers: bool is_prime(int x, std::atomic_bool & run) { (int = 2; < x && run; ++i) { if (x%i == 0) return false; } if (!run) { throw std::runtime_error("timeout"); } return true; } int main() { // call function asynchronously: std::atomic_bool run; run = true; std::future<bool> fut = std::async(is_prime, 700020007, std::ref(run)); // while waiting function set future: std::cout << "checking, please wait"; std::chrono::milliseconds span(100); while (fut.wait_for(span) == std::future_status::timeout) { std::cout << '.'; run = false; } try { bool x = fut.get(); std::cout << "\n700020007 " << (x ? "is" : "is not") << " prime.\n"; } catch (const std::runtime_error & ex) { // handle timeout here } return 0; }
why begin able stop thread bad.
stopping threads @ arbitrary point dangerous , lead resource leaks, resources being pointers, handles files , folders, , other things program should do.
when killing thread, thread may or may not doing work. whatever doing, won’t complete , variables created not destructors called because there no thread run them on.
Comments
Post a Comment