TEC
A lightweight C++ library enabling safe, efficient execution in multithreaded and concurrent systems.
Loading...
Searching...
No Matches
tec::Worker< TParams > Class Template Reference

A class implementing message processing as a daemon. More...

#include <tec_worker.hpp>

Inheritance diagram for tec::Worker< TParams >:
tec::Daemon tec::ActorWorker< TParams, TActor >

Public Types

using Params = TParams
 Type alias for worker parameters.
 
using id_t = std::thread::id
 Type alias for thread ID.
 
using Lock = std::lock_guard< std::mutex >
 Type alias for mutex lock guard.
 
using CallbackFunc = std::function< void(Worker< Params > *, const Message &)>
 Type alias for a callback function to process messages.
 

Public Member Functions

 Worker (const Params &params)
 Constructs a worker.
 
virtual ~Worker ()
 Destructor that ensures proper thread termination.
 
id_t id () const
 Retrieves the worker thread's ID.
 
constexpr const Paramsparams () const
 Retrieves the worker's configuration parameters.
 
const Signalsig_terminated () const override
 Retrieves the signal indicating the worker has terminated.
 
void send (Message &&msg) override
 Sends a message to the worker's queue.
 
Status make_request (Request &&req, Reply &&rep) override
 Sends a request and waits for a reply in a daemon thread.
 
template<typename Derived , typename T >
void register_callback (Derived *worker, void(Derived::*callback)(const Message &msg))
 Registers a callback for a specific message type.
 
Status run () override
 Starts the worker thread's message polling.
 
Status terminate () override
 Terminates the worker thread.
 
- Public Member Functions inherited from tec::Daemon
 Daemon ()=default
 Default constructor.
 
virtual ~Daemon ()=default
 Virtual destructor for safe polymorphic deletion.
 
 Daemon (const Daemon &)=delete
 Daemons are non-copyable to ensure unique ownership.
 
 Daemon (Daemon &&)=delete
 Daemons are non-movable to ensure unique ownership.
 
template<typename TRequest , typename TReply >
Status request (const TRequest *req, TReply *rep)
 Helper: Sends a request and waits for a reply in a daemon process.
 
template<typename TRequest >
Status request (const TRequest *req)
 Helper: Sends a notification request – no reply required.
 

Protected Member Functions

virtual void dispatch (const Message &msg)
 Dispatches a message to its registered callback.
 
virtual Status on_init ()
 Default callback invoked during worker thread initialization.
 
virtual Status on_exit ()
 Default callback invoked when exiting the worker thread.
 
virtual Status create_thread ()
 Create the Daemon's thread in suspended state.
 

Protected Attributes

Params params_
 Configuration parameters for the worker.
 

Detailed Description

template<typename TParams>
class tec::Worker< TParams >

A class implementing message processing as a daemon.

Implements the Daemon interface to manage a worker thread that processes messages from a SafeQueue. It supports registering callbacks for specific message types, provides default initialization and exit callbacks, and controls thread lifecycle with a signal for termination.

Template Parameters
TParamsThe type of parameters used to configure the worker.
Note
Workers are non-copyable and non-movable to ensure unique ownership.
See also
Daemon
Example: worker.hpp
Common header – defines TestWorker parameters and messages.
//
// worker.hpp -- a common header.
//
// Worker parameters.
struct TestParams {
// Add custom parameters.
};
// A compound message.
struct Position {
int x;
int y;
};
// Actual Worker implementation exposed as Daemon.
std::unique_ptr<tec::Daemon> create_test_worker(const TestParams&);
Defines the minimal contract for any long-lived service or processing component.
Example: worker.cpp
TestWorker implementation. Exposes the TestWorker Worker as a Daemon.
//
// worker.cpp -- TestWorker implementation.
//
#include "worker.hpp"
class TestWorker final: public tec::Worker<TestParams> {
public:
explicit TestWorker(const TestParams& params)
: tec::Worker<TestParams>{params}
{
// Register callbacks.
register_callback<TestWorker, int>(this, &TestWorker::process_int);
register_callback<TestWorker, std::string>(this, &TestWorker::process_string);
register_callback<TestWorker, Position>(this, &TestWorker::process_position);
}
// Process `int` message.
virtual void process_int(const tec::Message& msg) {
const int counter = std::any_cast<int>(msg);
// Do something with `counter`...
}
// Process `std::string` message.
virtual void process_string(const tec::Message& msg) {
auto str = std::any_cast<std::string>(msg);
// Do something with `str`...
}
// Process `Position` message.
virtual void process_position(const tec::Message& msg) {
auto pos = std::any_cast<Position>(msg);
// Do something with `pos.x` and `pos.y`...
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Expose actual Worker implementation as Daemon.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::unique_ptr<tec::Daemon> create_test_worker(const TestParams&) {
auto daemon{tec::Daemon::Builder<TestWorker>{}(params)};
return daemon;
}
};
A class implementing message processing as a daemon.
Definition tec_worker.hpp:70
Factory for creating daemon instances.
Definition tec_daemon.hpp:155
std::any Message
Type alias for a message that can hold any object.
Definition tec_message.hpp:43
Defines a worker class for processing messages in the tec namespace.
Example: run.cpp
Run the daemon.
//
// run.cpp -- run TestWorker as Daemon.
// NOTE: The actual TestWorker implementation is completely hidden.
// Compilation units `worker.cpp` and `main.cpp` are independent.
//
#include "worker.hpp"
tec::Status run_test_worker() {
TestParams params{};
// Create a daemon.
auto daemon = create_test_worker(params);
// Start the daemon thread and check for an initialization error.
auto status = daemon->run();
if( !status ) {
return status;
}
// Send different messages.
// `process_int` will be called in the Worker's thread.
daemon->send({7});
// `process_string` will be called in the Worker's thread.
daemon->send({std::string("This is a string!")});
// `process_position` will be called in the Worker's thread.
daemon->send({Position{2034, 710}});
// Optional -- if we want to check an exit status.
return daemon->terminate();
}
constexpr const Params & params() const
Retrieves the worker's configuration parameters.
Definition tec_worker.hpp:161
Defines error handling types and utilities for the tec namespace.

Member Typedef Documentation

◆ CallbackFunc

template<typename TParams >
using tec::Worker< TParams >::CallbackFunc = std::function<void(Worker<Params>*, const Message&)>

Type alias for a callback function to process messages.

Defines a function that takes a Worker pointer and a Message to process.

Constructor & Destructor Documentation

◆ Worker()

template<typename TParams >
tec::Worker< TParams >::Worker ( const Params params)
inlineexplicit

Constructs a worker.

Initializes the worker with the provided parameters. The worker thread is created by calling run().

Parameters
paramsThe configuration parameters for the worker.
See also
run()

◆ ~Worker()

template<typename TParams >
virtual tec::Worker< TParams >::~Worker ( )
inlinevirtual

Destructor that ensures proper thread termination.

Calls terminate() if the thread is joinable to ensure clean shutdown.

Member Function Documentation

◆ dispatch()

template<typename TParams >
virtual void tec::Worker< TParams >::dispatch ( const Message msg)
inlineprotectedvirtual

Dispatches a message to its registered callback.

Looks up the callback for the message's type in the slots table and invokes it if found.

Parameters
msgThe message to dispatch.
See also
register_callback()

◆ id()

template<typename TParams >
id_t tec::Worker< TParams >::id ( ) const
inline

Retrieves the worker thread's ID.

Returns
id_t The ID of the worker thread.

◆ make_request()

template<typename TParams >
Status tec::Worker< TParams >::make_request ( Request &&  req,
Reply &&  rep 
)
inlineoverridevirtual

Sends a request and waits for a reply in a daemon thread.

This method sends an RPC-style request of type Payload to the daemon and waits for a corresponding reply of type Reply. It uses a signal to synchronize the operation and returns the status of the request processing.

Parameters
reqThe request object to be sent.
repThe reply object where the response will be stored.
Returns
Status The status of the request operation, indicating success or an error.
See also
Actor::process_request()
ActorWorker

Implements tec::Daemon.

◆ on_exit()

template<typename TParams >
virtual Status tec::Worker< TParams >::on_exit ( )
inlineprotectedvirtual

Default callback invoked when exiting the worker thread.

Called after the message loop, only if on_init() succeeded.

Returns
Status Error::Kind::Ok by default.

Reimplemented in tec::ActorWorker< TParams, TActor >.

◆ on_init()

template<typename TParams >
virtual Status tec::Worker< TParams >::on_init ( )
inlineprotectedvirtual

Default callback invoked during worker thread initialization.

Called before entering the message loop. If it returns a status other than Error::Kind::Ok, the worker stops and skips the message loop and on_exit().

Returns
Status Error::Kind::Ok by default.

Reimplemented in tec::ActorWorker< TParams, TActor >.

◆ params()

template<typename TParams >
constexpr const Params & tec::Worker< TParams >::params ( ) const
inlineconstexpr

Retrieves the worker's configuration parameters.

Returns
const Params& The worker's parameters.

◆ register_callback()

template<typename TParams >
template<typename Derived , typename T >
void tec::Worker< TParams >::register_callback ( Derived worker,
void(Derived::*)(const Message &msg callback 
)
inline

Registers a callback for a specific message type.

Associates a member function of a derived class with a message type. The callback is stored in the slots table and invoked when a matching message is received. Should not be called while the worker is running.

Template Parameters
DerivedThe derived worker class type.
TThe message type to associate with the callback.
Parameters
workerPointer to the derived worker instance.
callbackThe member function to call for the message type.
See also
dispatch()

◆ run()

template<typename TParams >
Status tec::Worker< TParams >::run ( )
inlineoverridevirtual

Starts the worker thread's message polling.

Creates the worker thread, signals sig_running_, and waits for initialization to complete. Returns the initialization status.

Returns
Status The result of the initialization.
See also
Daemon::run()

Implements tec::Daemon.

◆ send()

template<typename TParams >
void tec::Worker< TParams >::send ( Message &&  msg)
inlineoverridevirtual

Sends a message to the worker's queue.

Enqueues a message for processing if the worker thread is joinable. Logs the operation using tracing if enabled.

Parameters
msgThe message to send.
See also
Daemon::send()

Implements tec::Daemon.

◆ sig_terminated()

template<typename TParams >
const Signal & tec::Worker< TParams >::sig_terminated ( ) const
inlineoverridevirtual

Retrieves the signal indicating the worker has terminated.

Returns
const Signal& The termination signal.
See also
Daemon::sig_terminated()

Implements tec::Daemon.

◆ terminate()

template<typename TParams >
Status tec::Worker< TParams >::terminate ( )
inlineoverridevirtual

Terminates the worker thread.

Sends a null message to stop the message loop if initialized successfully, waits for termination, and joins the thread. Should not be called from the worker thread.

Returns
Status The final status of the worker.
See also
Daemon::terminate()
nullmsg()

Implements tec::Daemon.


The documentation for this class was generated from the following file: