#pragma once /////////////////////////////////////////////////////////////////////// // Stoppable.h - run function asynchronously, passing a stop signal // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2016 // /////////////////////////////////////////////////////////////////////// #include #include #include /////////////////////////////////////////////////////////////////////// // Stoppable class runs callable object asynchronously // - Callable Object must accept an atomic stop signal template class Stoppable { public: std::thread asyncRun(CallObj& co); void stop(); private: std::atomic doStop = false; }; //----< run callable object on child thread >-------------------------- template std::thread Stoppable::asyncRun(CallObj& co) { // lambda acquires callable object co and // member field doStop by reference std::function f = [&]() { co(doStop); }; std::thread t(f); return t; } //----< signal stop by changing value of doStop to true >-------------- template void Stoppable::stop() { doStop.store(true); // this is an atomic operation }