C++ how to implment a stoppable future function call? -
i want execute function after timeout period, like:
sleep(1000); dowork();
but before timeout reached, can stop execution in thread or other thread, like:
if(somecondition) { stop dowork() not started. }
is there existing std/boost class kind of task?
you may use combination of variable indicating whether work needs done combined timed condition variable: you'd wait sleep time , if wait terminates you'd check if work should aborted, more sleeping needed (condition variables can stop waiting spuriously), or work can started:
bool do_work(true); std::mutex mutex; std::condition_variable condition; std::chrono::time_point<std::chrono::steady_clock> abs_time( std::chrono::steady_clock::now() + std::chrono::milliseconds(1000)); std::unique_lock<std::mutex> kerberos; if (condition.wait_until(kerberos, abs_time, [&]{ return do_work; })) { // work }
the other thread cancelling work acquire lock mutex, set do_work
false
, , notify_one()
condition variable.
Comments
Post a Comment