qb  2.0.0.0
C++17 Actor Framework
qb Issue Watch Star Fork Follow @isndev
Loading...
Searching...
No Matches
Engine & Scheduling

Manages actor execution, virtual cores, and system lifecycle. More...

Collaboration diagram for Engine & Scheduling:

Files

file  main.h
 Convenience header for the QB Main engine controller.

Classes

class  qb::CoreInitializer
 Handles pre-start configuration for a single VirtualCore. More...
class  qb::CoreInitializer::ActorBuilder
 Helper to fluently build multiple Actors for a CoreInitializer. More...
class  qb::SharedCoreCommunication
 Manages inter-core communication infrastructure (mailboxes). More...
struct  qb::CoreSpawnerParameter
 Internal structure for passing parameters to core spawning functions. More...
class  qb::Main
 The main controller for the QB Actor Framework engine. More...
class  qb::VirtualCore
 Manages a virtual processing core (worker thread) in the actor system. More...

Typedefs

using qb::CoreInitializerMap = qb::unordered_map<CoreId, CoreInitializer>
 Map of CoreId to CoreInitializer objects.
using qb::engine = Main
 Alias for the Main class.

Enumerations

enum  qb::VirtualCore::Error : uint64_t { qb::VirtualCore::BadInit = (1u << 9u) , qb::VirtualCore::NoActor = (1u << 10u) , qb::VirtualCore::BadActorInit = (1u << 11u) , qb::VirtualCore::ExceptionThrown = (1u << 12u) }
 Error codes for virtual core operations and states. These flags can be combined to represent multiple error conditions. More...

Functions

void qb::SharedCoreCommunication::Mailbox::wait () noexcept
 Waits for a notification on this mailbox, up to its configured latency.
void qb::SharedCoreCommunication::Mailbox::notify () noexcept
 Notifies a waiting thread (VirtualCore) that an event might be available in this mailbox.
uint64_t qb::SharedCoreCommunication::Mailbox::getLatency () const noexcept
 Get the latency setting for this mailbox.
bool qb::SharedCoreCommunication::send (Event const &event) const noexcept
 Send an event to the mailbox of its destination VirtualCore.
Mailbox & qb::SharedCoreCommunication::getMailBox (CoreId id) const noexcept
 Get the mailbox for a specific VirtualCore.
CoreId qb::SharedCoreCommunication::getNbCore () const noexcept
 Get the number of VirtualCores configured in the system.
void qb::Main::start (bool async=true) noexcept
 Start the engine and its VirtualCore worker threads.
bool qb::Main::hasError () const noexcept
 Check if any VirtualCore encountered an error and terminated prematurely.
static void qb::Main::stop () noexcept
 Stop the engine and all its VirtualCores gracefully.
void qb::Main::join ()
 Wait for the engine and all its VirtualCore threads to terminate.
template<typename _Actor, typename... _Args>
ActorId qb::Main::addActor (CoreId index, _Args &&...args)
 Add a new actor to a specified VirtualCore before the engine starts.
CoreInitializerqb::Main::core (CoreId index)
 Get the CoreInitializer for a specific VirtualCore index.
void qb::Main::setLatency (uint64_t latency=0)
 Set the default event loop latency for all VirtualCores.
qb::CoreIdSet qb::Main::usedCoreSet () const
 Get the set of CoreIds that are currently configured to be used by the engine.
static void qb::Main::registerSignal (int signum) noexcept
 Register a system signal to be handled by the engine (results in graceful shutdown).
static void qb::Main::unregisterSignal (int signum) noexcept
 Unregister a previously registered system signal from engine handling.
static void qb::Main::ignoreSignal (int signum) noexcept
 Ignore a system signal, preventing the engine or default OS handler from processing it.
CoreId qb::VirtualCore::getIndex () const noexcept
 Get the core's index.
const CoreIdSetqb::VirtualCore::getCoreSet () const noexcept
 Get the set of cores this VirtualCore is configured to communicate with.
uint64_t qb::VirtualCore::time () const noexcept
 Get the current cached time for this VirtualCore's processing loop.

Variables

constexpr const CoreId qb::NoAffinity = std::numeric_limits<CoreId>::max()
 Special constant indicating that no CPU affinity is desired.

Detailed Description

Manages actor execution, virtual cores, and system lifecycle.

Contains `qb::Main` for engine control, `qb::VirtualCore` for actor execution, and `qb::CoreSet` for CPU affinity.

Typedef Documentation

◆ CoreInitializerMap

Map of CoreId to CoreInitializer objects.

This container maps core identifiers to their respective initializer objects, providing a way to store and access configuration for all VirtualCores in the system.

◆ engine

using qb::engine = Main

Alias for the Main class.

Provides a concise alternative name for the main engine class. This is provided for naming consistency with other lowercase aliases in the framework.

Enumeration Type Documentation

◆ Error

enum qb::VirtualCore::Error : uint64_t

Error codes for virtual core operations and states. These flags can be combined to represent multiple error conditions.

Enumerator
BadInit 

General initialization error for the VirtualCore.

NoActor 

An expected actor was not found or couldn't be processed.

BadActorInit 

An actor's onInit() method returned false or threw an exception.

ExceptionThrown 

An unhandled exception occurred during VirtualCore execution (e.g., in an actor event handler).

Function Documentation

◆ wait()

void qb::SharedCoreCommunication::Mailbox::wait ( )
inlinenoexcept

Waits for a notification on this mailbox, up to its configured latency.

If the mailbox is configured with a non-zero latency (_latency > 0), this method blocks the calling thread (typically a VirtualCore's event loop) using a std::condition_variable for a duration up to _latency nanoseconds, or until notify() is called. If _latency is 0, this method returns immediately (effectively a no-op for waiting). This is used by VirtualCores to sleep when idle, reducing CPU usage.

◆ notify()

void qb::SharedCoreCommunication::Mailbox::notify ( )
inlinenoexcept

Notifies a waiting thread (VirtualCore) that an event might be available in this mailbox.

If the mailbox is configured with a non-zero latency (_latency > 0), this method signals the std::condition_variable associated with this mailbox. This wakes up a VirtualCore thread that might be sleeping in the wait() method, prompting it to check the mailbox for new events. If _latency is 0, this method is a no-op.

◆ getLatency()

uint64_t qb::SharedCoreCommunication::Mailbox::getLatency ( ) const
inlinenodiscardnoexcept

Get the latency setting for this mailbox.

Returns
The configured latency in nanoseconds. If 0, the mailbox operates in a low-latency (busy-spin) mode for its consumer.

◆ send()

bool qb::SharedCoreCommunication::send ( Event const & event) const
nodiscardnoexcept

Send an event to the mailbox of its destination VirtualCore.

Parameters
eventThe qb::Event to send. The event's dest_core() determines the target mailbox.
Returns
true if the event was successfully enqueued into the destination core's mailbox. false if the destination core ID is invalid, the mailbox is full (rare), or another error occurred during enqueueing.

This method is used internally by actors and the engine to route events between cores. It relies on the MPSC ringbuffer implementation for the mailboxes.

◆ getMailBox()

Mailbox & qb::SharedCoreCommunication::getMailBox ( CoreId id) const
nodiscardnoexcept

Get the mailbox for a specific VirtualCore.

Parameters
idThe CoreId of the VirtualCore whose mailbox is requested.
Returns
Reference to the Mailbox object for the specified core.
Note
This provides direct access to the inter-core communication channel. Used internally. Throws std::out_of_range if id is invalid.

◆ getNbCore()

CoreId qb::SharedCoreCommunication::getNbCore ( ) const
nodiscardnoexcept

Get the number of VirtualCores configured in the system.

Returns
The total number of CoreIds managed by this SharedCoreCommunication instance, which corresponds to the number of VirtualCores the engine will run.

◆ start()

void qb::Main::start ( bool async = true)
noexcept

Start the engine and its VirtualCore worker threads.

Parameters
asyncIf true (default), the engine starts asynchronously, and this call returns immediately. The main application thread continues execution. join() should be called later to wait. If false, the calling thread becomes one of the VirtualCore worker threads (typically core 0). This call will block until the engine is stopped.
Note
All actors and core configurations (affinity, latency) must be set up before calling start().

◆ hasError()

bool qb::Main::hasError ( ) const
nodiscardnoexcept

Check if any VirtualCore encountered an error and terminated prematurely.

Returns
true if an error occurred in one or more cores, false otherwise.
Note
This should typically be checked after join() returns.

◆ stop()

void qb::Main::stop ( )
staticnoexcept

Stop the engine and all its VirtualCores gracefully.

This is a static method and can be called from any thread, including signal handlers. It signals all VirtualCores to shut down. Actors will typically receive a KillEvent.

Note
Same effect as receiving a SIGINT or SIGTERM signal by default.

◆ join()

void qb::Main::join ( )

Wait for the engine and all its VirtualCore threads to terminate.

This function blocks until the engine has fully shut down. It should be called if start(true) (asynchronous start) was used.

◆ addActor()

template<typename _Actor, typename... _Args>
ActorId qb::Main::addActor ( CoreId index,
_Args &&... args )

Add a new actor to a specified VirtualCore before the engine starts.

Template Parameters
_ActorDerivedActor type to create.
_ArgsArguments to forward to the constructor of the _Actor.
Parameters
indexThe CoreId of the VirtualCore to add this actor to.
argsArguments to forward to the _Actor\'s constructor.
Returns
ActorId of the created _Actor. Returns ActorId::NotFound on failure.

A convenience method that is equivalent to core(index).addActor<_Actor>(args...). Example:

// qb::Main engine;
// auto id = engine.addActor<MyActor>(0, param1, param2);
Attention
This function is only available before the engine is running.

◆ core()

CoreInitializer & qb::Main::core ( CoreId index)
nodiscard

Get the CoreInitializer for a specific VirtualCore index.

Parameters
indexThe CoreId of the VirtualCore to configure.
Returns
Reference to the CoreInitializer for the specified core.

Allows setting core-specific properties like affinity and latency before starting the engine.

Attention
This function is only available before the engine is running. The returned reference is to an object managed by qb::Main.
// qb::Main engine;
// qb::CoreInitializer& core_config = engine.core(0);
// core_config.setLatency(100000); // 100us

◆ setLatency()

void qb::Main::setLatency ( uint64_t latency = 0)

Set the default event loop latency for all VirtualCores.

Parameters
latencyThe maximum time in nanoseconds for cores to wait when idle. 0 means no wait (low latency mode).

This sets the latency for all cores that haven\'t had a specific latency set via CoreInitializer::setLatency().
See CoreInitializer::setLatency() for more details on latency values.

Attention
This function is only available before the engine is running.

◆ usedCoreSet()

qb::CoreIdSet qb::Main::usedCoreSet ( ) const
nodiscard

Get the set of CoreIds that are currently configured to be used by the engine.

Returns
A qb::CoreIdSet containing the IDs of all cores that will be launched.

This reflects the cores for which CoreInitializer objects exist, typically based on the arguments passed to the Main constructor or default hardware concurrency.

◆ registerSignal()

void qb::Main::registerSignal ( int signum)
staticnoexcept

Register a system signal to be handled by the engine (results in graceful shutdown).

Parameters
signumThe signal number (e.g., SIGUSR1, SIGHUP).
Note
By default, SIGINT and SIGTERM (on non-Windows platforms) are registered to call Main::stop().
Registered signals will trigger a graceful shutdown of all actors.
This is a static method and affects all Main instances if multiple were to exist (though typically only one exists).

◆ unregisterSignal()

void qb::Main::unregisterSignal ( int signum)
staticnoexcept

Unregister a previously registered system signal from engine handling.

Parameters
signumThe signal number to unregister.

After unregistering, the default OS behavior for that signal will apply if it occurs.
This is a static method.

◆ ignoreSignal()

void qb::Main::ignoreSignal ( int signum)
staticnoexcept

Ignore a system signal, preventing the engine or default OS handler from processing it.

Parameters
signumThe signal number to ignore (e.g., SIGPIPE).

This is a static method.

◆ getIndex()

CoreId qb::VirtualCore::getIndex ( ) const
nodiscardnoexcept

Get the core's index.

Returns
CoreId (unsigned short) representing the unique index of this VirtualCore.

This ID is assigned during engine initialization and is used in ActorId construction.

◆ getCoreSet()

const CoreIdSet & qb::VirtualCore::getCoreSet ( ) const
nodiscardnoexcept

Get the set of cores this VirtualCore is configured to communicate with.

Returns
Const reference to a CoreIdSet.

This set typically includes all other VirtualCores in the system, allowing this core to send events to actors on those cores.

◆ time()

uint64_t qb::VirtualCore::time ( ) const
nodiscardnoexcept

Get the current cached time for this VirtualCore's processing loop.

Returns
uint64_t timestamp in nanoseconds since epoch.

This timestamp is updated once at the beginning of each iteration of the VirtualCore's main processing loop. All actors running on this core during that single iteration will see the same value when calling Actor::time() (which internally calls this). This is optimized for performance within a loop iteration but means it does not update with true nanosecond precision during a single actor's event handling. For a continuously updating high-precision clock, use qb::NanoTimestamp().

Variable Documentation

◆ NoAffinity

const CoreId qb::NoAffinity = std::numeric_limits<CoreId>::max()
constexpr

Special constant indicating that no CPU affinity is desired.

Used with setAffinity functions to indicate that a VirtualCore should not be restricted to specific CPU cores, letting the operating system handle thread scheduling.