Cbeam
Loading...
Searching...
No Matches
cbeam/concurrency/threaded_object.hpp

Base class for creating and managing a thread. This class follows the Curiously Recurring Template Pattern (CRTP) to allow derived classes to implement their specific worker logic.

Base class for creating and managing a thread. This class follows the Curiously Recurring Template Pattern (CRTP) to allow derived classes to implement their specific worker logic. The first argument of the inherited class’ constructor needs to be the private threaded_object::construction_token to prevent construction without threaded_object::create.

class MyThreadedObject : threaded_object<MyThreadedObject>
{
public:
const int demo_parameter)
: threaded_object<MyThreadedObject>{_mtx, _cv}
{
}
void worker()
{
while (this->is_running())
{
{
std::unique_lock<std::mutex> lock(_mtx);
// We may have missed a notification during previous work
// outside this lock, so check the `ready' shared variable
// and the running state before waiting for a notification.
if (!ready && this->is_running())
{
// Wait for other thread to notify us
// via _cv->notify_one() or _cv->notify_all().
_cv->wait(lock, [&]
{
return ready || !this->is_running();
});
}
}
// Either
// (1) ready has been set to true by another thread
// (==> do some work here), or
// (2) _running has been set to false by the base class,
// which notified us.
}
}
private:
std::mutex _mtx;
std::condition_variable _cv;
bool ready{false}; // sample shared variable
}

See https://en.cppreference.com/w/cpp/thread/condition_variable The method worker needs to be public to enable creation via static method threaded_object::create().

Template Parameters
DerivedThe derived class which implements the worker method.