Files CCore/inc/StartStop.h CCore/src/StartStop.cpp
The class StartStopObject is designed to start and stop active objects. An active object is the object with one or several associated working thread.
template <class T>
class StartStopObject : NoCopy
{
T &obj;
Sem stop_sem;
public:
template <class ... TT>
StartStopObject(T &obj_,TT ... tt);
~StartStopObject();
};
The working thread is started by the constructor, and destructor ensures it is finished. An additional arguments can be used to control thread properties (see Task constructor arguments).
The class T must provide the following methods:
class ActiveClass { public: void prepareRun(); void objRun(); void completeRun() noexcept; void signalStop(); void completeStop(); };
prepareRun() is called before starting a thread. It may throw an exception, if the object cannot be started.
objRun() is the working method, it is called in the working thread.
completeRun() is called after successful start of the thread. It must not throw exceptions.
signalStop() is called to signal to the object to stop execution.
completeStop() is called after the thread is stopped.
These methods are called in the shown order (except objRun()).
Here is an example:
class Device : NoCopy { Atomic stop_flag; Mutex mutex; bool running; // void set(bool running_) { Mutex::Lock lock(mutex); running=running_; } // object run public: void prepareRun() { stop_flag=0; } void objRun() { set(true); while( !stop_flag ) { // doing something } } void completeRun() noexcept { set(true); } // we set running flag either way void signalStop() { stop_flag=1; } void completeStop() { set(false); } }; .... Device device; { StartStopObject start_stop(device); // do something, device is working here too } // device is stopped on the scope exit