Overview / System & concurrency

event

Signals and an event bus with no <code>std::function</code> and no <code>shared_ptr</code>. A slot is a context and function pointer pair in a contiguous vector. Reentrancy is handled.

Always compiled: part of the core build.Include #include <ethereal/cpp/event/event_inc.hpp>C layer

event_inc.hpp

#include <ethereal/cpp/event/event_inc.hpp>

Umbrella header of the Events module.

Observer and event bus. The module exists because the pattern was already written by hand and locked inside its users: 'assert.hpp' has a listener table with priority, removal by id and a snapshot before notifying. Correct, and out of reach of everyone else.

The six rules (disconnecting during emission, surviving one's own disconnection, whoever connects during emission waits for the next one, connection order, exceptions propagate, and what is or is not thread safe) are written out at the top of 'event.hpp'. None of them is an implementation detail.

Which one to use:

  • Ethereal::Events::CSignal : the emitter knows the listening point. Typed, direct, no allocation per emission.
  • Ethereal::Events::CEventBus : the emitter only knows the type of the event. That is what lets the network announce "connection dropped" without including anything of the user interface.
  • Ethereal::Events::CScopedConnection : ties the disconnection to a scope, for the classic accident of the observer that dies still connected.

The difference between 'Publish' and 'Post' matters: the first delivers on the stack of the caller, the second queues a copy and is the only safe path between threads.

Including this header brings the whole module.

bus.hpp

#include <ethereal/cpp/event/bus.hpp>

Event bus of the Events module: publish by type, without the emitter and the receiver knowing each other.

The difference from a signal is who knows whom. With a signal, the emitter holds the object and so knows the listening point. With the bus, the emitter only knows the type of the event. That is what lets the network module announce "connection dropped" without including anything of the user interface.

The address of a type does not work as an index, and that is why there is a counter. The spec: "Type identity uses a compile-time monotonic type ID (address of a static per-type variable, or a counter assigned at static init), and the bus dispatches through a dense array indexed by that ID, not a hash map." The previous version used the address of a static variable per type. It works as an identity and not as an index: sixty four bits spread over the address space, and reaching the signal needs a map, exactly what the spec forbids on the dispatch path. A counter assigned at static initialization gives numbers 0, 1, 2, ... and dispatch becomes one vector index.

'Publish' and 'Post', and the difference that matters. CEventBus::Publish delivers now, on the stack of the caller. A handler that publishes another event is served from inside the first one. CEventBus::Post copies the bytes into a ring and delivery only happens in CEventBus::Drain. That is why it only accepts trivially copyable types, and that is a compile time refusal, not a warning: "'Post' serializes the event into a per-thread MPSC queue of trivially copyable POD events only. Non-trivial event types are a compile error on 'Post'. This keeps the queue a flat byte ring with no per-event allocation and no type erasure cost on drain."

function

NextTypeId

Ethereal::Events::Reserved#
ETL_UINT32 NextTypeId() noexcept;

Hands out the next type number. One per type, starting at zero.

struct

SType

Ethereal::Events::Reserved#
C++
template< typename T >
struct   SType
{
    /// @brief  The type number.
    static const ETL_UINT32        s_uId;
};

The number of this type, assigned at static initialization.

function

NextTypeId

Ethereal::Events::Reserved#
template< typename T > const ETL_UINT32 SType< T >::s_uId = NextTypeId();
function

TypeIdOf

Ethereal::Events#
template< typename T > inline ETL_UINT32 TypeIdOf() noexcept
class

IDispatcher

Ethereal::Events#

Takes a CEventBus::Post to be delivered somewhere else.

class IDispatcher

The spec asks for this as optional: "Optional 'IDispatcher' seam so 'Post' can hand off to a thread pool from Concurrency. The Event module does not link Concurrency. Default dispatcher is the caller pumping 'Drain' on their own thread."

destructor

~IDispatcher

#
virtual ~IDispatcher() = default;

Destructor.

function

OnWorkPosted

#
virtual void OnWorkPosted() noexcept = 0;

There is work in the queue. Called from inside Post.

Must not throw, and must not call Drain back from inside itself.
class

CEventBus

Ethereal::Events#

The event bus.

class CEventBus final
constructor

CEventBus

#
CEventBus();

Constructor. Reserves the queue ring.

function

Subscribe

#
template< typename TEvent > SConnection Subscribe( void * const pContext, void ( * const pfn )( void *, const TEvent & ) ) noexcept

Starts receiving events of this type.

If there is already a sticky event of this type, it is delivered to this subscriber right away, from inside this call. That is what makes sticky events useful for state: whoever arrives late catches up.

pContext
The context, passed back on each delivery.
pfn
What to call. Context first, event by reference.
The connection, invalid on failure.
function

SubscribeFiltered

#
template< typename TEvent > SConnection SubscribeFiltered( void * const pContext, bool ( * const pfnPredicate )( void *, const TEvent & ), void ( * const pfn )( void *, const TEvent & ) ) noexcept

Starts receiving, but only what passes the filter.

The filter runs before the handler and before any copy, which is what the spec asks. A subscriber that only wants the events of one player does not pay for the work of the others.

pContext
The context, passed back on each call.
pfnPredicate
The filter. true lets the event through.
pfn
The handler.
The connection, invalid on failure.
function

Unsubscribe

#
bool Unsubscribe( SConnection Conn ) noexcept;

Undoes a subscription.

function

UnsubscribeAll

#
void UnsubscribeAll() noexcept;

Undoes all of them.

function

SubscriberCount

#
template< typename TEvent > std::size_t SubscriberCount() const noexcept

Number of subscribers of this type.

function

Publish

#
template< typename TEvent > void Publish( const TEvent & Event ) noexcept

Delivers now, on the stack of the caller.

function

Post

#
template< typename TEvent > bool Post( const TEvent & Event ) noexcept

Queues a copy of the bytes. Delivery happens in Drain.

false when the queue is full. See SetQueueLimit.
function

PublishSticky

#
template< typename TEvent > bool PublishSticky( const TEvent & Event ) noexcept

Publishes now and keeps it as the last value of this type.

Whoever subscribes later receives it at once. It is meant for state ("the server is up", "the window has this size"), not for happenings.

function

ClearSticky

#
template< typename TEvent > bool ClearSticky() noexcept

Forgets the sticky event of this type.

function

Drain

#
std::size_t Drain( std::size_t uMax = 0 ) noexcept;

Delivers what is in the queue.

uMax
Maximum number to deliver. Zero means all.
How many were delivered.
function

Pending

#
std::size_t Pending() const noexcept;

How many are waiting.

function

ClearQueue

#
void ClearQueue() noexcept;

Empties the queue without delivering anything.

function

SetQueueLimit

#
void SetQueueLimit( std::size_t uBytes ) noexcept;

How many bytes the queue can hold. Zero restores the default. Empties the queue.

function

DroppedPosts

#
ETL_UINT64 DroppedPosts() const noexcept;

How many Post calls were refused for lack of room.

function

SetDispatcher

#
void SetDispatcher( IDispatcher * pDispatcher ) noexcept;

Who to notify when there is work. Null disables it.

const

RAW_BASE

#
static constexpr ETL_UINT32 RAW_BASE = 0x40000000u;

Marker of the raw range. Does not collide with TypeIdOf.

alias

void

#
using RawFn = void ( * )( void *, const void *, std::size_t );

The signature of a raw slot: context, bytes, size.

function

SubscribeRaw

#
SConnection SubscribeRaw( ETL_UINT32 uType, void * pContext, RawFn pfn ) noexcept;

Subscribes to a type number chosen by the caller.

function

PublishRaw

#
void PublishRaw( ETL_UINT32 uType, const void * pBytes, std::size_t uBytes ) noexcept;

Delivers now, to whoever subscribed to that number.

function

PostRaw

#
bool PostRaw( ETL_UINT32 uType, const void * pBytes, std::size_t uBytes ) noexcept;

Queues a copy of the bytes.

function

PublishStickyRaw

#
bool PublishStickyRaw( ETL_UINT32 uType, const void * pBytes, std::size_t uBytes ) noexcept;

Publishes and keeps it as the last value of that number.

function

ClearStickyRaw

#
bool ClearStickyRaw( ETL_UINT32 uType ) noexcept;

Forgets the sticky event of that number.

function

SubscribeFilteredRaw

#
SConnection SubscribeFilteredRaw( ETL_UINT32 uType, void * pContext, int ( * pfnPredicate )( void *, const void *, std::size_t ), RawFn pfn ) noexcept;

Subscribes with a filter, with the type number coming from outside.

function

SubscriberCountRaw

#
std::size_t SubscriberCountRaw( ETL_UINT32 uType ) const noexcept;

Number of subscribers of that number.

alias

void

#
using PublishFn = void ( * )( CSignalCore &, const void *, const void * );

Typed publisher of an event type: core, event, extra argument.

alias

void

#
using FilteredFn = void ( * )( void *, CSignalCore::GenericFn, CSignalCore::GenericFn, const void *, std::size_t );

Caller of a filtered subscriber.

The size goes along, and the typed filtered caller ignores it. It knows the size of its type. The raw door is what needs it, where the event is bytes and the size is only known on publication.

concurrent.hpp

#include <ethereal/cpp/event/concurrent.hpp>

Thread safe signal of the Events module.

The thread safe variant is a separate type, not a flag. The spec is explicit, and the reason is design, not taste: "The thread-safe variant is a separate type, not a runtime flag. 'CSignal' has no synchronization at all, 'CConcurrentSignal' pays for what it uses. Do not make the single-threaded user pay for an atomic." A runtime flag would put a branch, and worse a shared read, on the path the spec wants under two nanoseconds. Whoever does not need synchronization cannot pay for it, and the only way to guarantee that is not having the code there.

What this variant guarantees: connecting, disconnecting and emitting from different threads does not corrupt the list. And from inside a slot, on the emitting thread, the reentrancy of 'CSignal': connecting, disconnecting and emitting the same signal again.

What it does not guarantee: that the handler is safe. If two slots touch the same data, that is their problem, this type protects the list, not what the slots do. Nor any order between threads. Two 'Emit' calls at the same time serialize, and the first one is whoever reaches the lock first.

Why a lock and not a lock free list: a lock free list for this case would need epoch based reclamation or hazard pointers. That is what the Plugin module does for its table, and there it is justified because the alternative is a certain crash. Here the alternative is a lock on an emission that is about to call outside code anyway. The lock costs much less than the call that follows, and the path of whoever does not need this (the 'CSignal') still pays nothing. It is the wrong type for a tight loop, and that is stated here.

class

CConcurrentSignal

Ethereal::Events#

A signal that supports connecting, disconnecting and emitting from different threads.

template< typename... TArgs > class CConcurrentSignal

See the note at the top of the file about what this guarantees and what it does not. For the single thread case, which is the vast majority, use CSignal, which pays nothing for this.

alias

void

#
using SlotFn = void ( * )( void *, TArgs... );

The signature of a slot: context first, then the arguments.

constructor

CConcurrentSignal

#
CConcurrentSignal() = default;

Default constructor. No slots, no allocation.

function

Connect

#
SConnection Connect( void * const pContext, const SlotFn pfn )

Connects a free function with a context, under the lock.

pContext
Passed back on each call.
pfn
The function.
The connection, invalid on failure.
function

Disconnect

#
bool Disconnect( const SConnection Conn )

Undoes a connection, under the lock.

function

DisconnectAll

#
void DisconnectAll()

Undoes all of them, under the lock.

function

Emit

#
void Emit( TArgs... Args )

Calls every connected slot, with the list locked.

The fast guard still exists, and it is a relaxed atomic read. A signal with nobody listening never touches the lock, which is the common case and would be a pity to pay for.

The relaxed read can see a value from an instant ago. That is acceptable and not careless: whoever connects a slot on another thread at the same instant this one emits has no way to know whether it got in before or after. It is a race of the caller, not of this class.

A slot may emit the same signal again, on the same thread. The nested emission follows the rules of CSignal: it walks the slots live at its own entry, and what is connected or disconnected inside is applied when the outermost emission ends. It runs under the lock the outer one already holds.

function

SlotCount

#
std::size_t SlotCount() const noexcept

Number of live slots.

function

IsEmpty

#
bool IsEmpty() const noexcept

No live slot.

event.hpp

#include <ethereal/cpp/event/event.hpp>

Main header of the Events module: the six rules, the connection id and the type tag without RTTI.

This module exists because the pattern was already written by hand inside the library, and locked there. 'assert.hpp' has a fixed capacity listener table, ordering by priority, removal by id and a snapshot of the table before notifying, precisely to survive a listener that removes itself during notification. That code is correct and nobody else can reach it. The 'CJobManager', the event loop and the RUDP each keep their own 'std::function' objects and each solves the same problem in a different way.

The problem is not "calling a stored function". It is what happens around it, and that is where this kind of code breaks. The six rules below are the contract of the module.

1. Disconnecting during emission is legitimate and must not corrupt the iteration. The most common case of all: the handler does its work and disconnects. If the emission is walking a vector, removing in the middle invalidates what it holds. Here a disconnection during emission only marks the slot as dead. The real removal happens when the outermost emission ends. Meanwhile, dead slots are skipped.

2. A handler survives its own disconnection until it returns. A handler that calls CSignal::Disconnect with its own id would, in a naive design, destroy the object running at that moment. Here a slot is a pair of plain pointers (function and context) and the signal owns no callable. A disconnection during an emission only turns the slot into a tombstone, and the tombstones are collected after the outermost emission ends (see rule 1). The vector is never compacted while it is being walked.

3. Whoever connects during an emission is not called by it. The number of slots is frozen at the start of the emission. Without this rule, a handler that connects itself produces an infinite loop, and the difference between "called in this round" and "called in the next" depends on the order in which the connections were made, the kind of thing that changes on its own months later. Same run to completion rule as the state machine.

4. The order is the connection order, and that is a contract. First to connect, first to be called. A priority exists (CSignal::ConnectWithPriority, lower comes first), but only whoever asks for it pays for the sorting. Without it the order is the connection order. Whoever needs order and does not want to fight over a range of numbers connects in order.

5. A handler exception propagates, and the following handlers do not run. Swallowing the exception would leave the program running with half of the effect applied and nothing written anywhere, the worst of both worlds. It propagates, and the internal state of the emission is correctly undone on the way up, so the signal remains usable.

6. There is no thread safety guarantee, with one explicit exception. CSignal and the subscriber list of CEventBus belong to one thread. Locking every emission would cost exactly on the hot path, and locking only sometimes would be worse than not locking. The exception is CEventBus::Post, which is thread safe: it is the real case of a network reply arriving on an event loop thread and needing to be handled on the application thread. Only the queue is protected. Delivery happens in CEventBus::Drain, on the thread of the caller. Whoever needs a signal shared by threads uses CConcurrentSignal, a separate type. On the emitting thread it keeps rules 1 to 3, emitting the same signal again from inside a slot included.

alias

ConnectionId

Ethereal::Events#
using ConnectionId = ETL_UINT64;

Identifier of a connection.

Returned by Connect and Subscribe, it is what is passed to disconnect. It is never reused: the id of a connection already undone never becomes valid for another one, so disconnecting twice is harmless and returns false the second time.

const

INVALID_CONNECTION

Ethereal::Events#
constexpr ConnectionId INVALID_CONNECTION = 0;

The value no connection has.

alias

TypeId

Ethereal::Events#
using TypeId = const void *;

Type tag, used by the bus to tell which event is which.

struct

STypeTag

Ethereal::Events::Reserved#
C++
template< typename T >
struct STypeTag
{
    /// @brief  The byte whose address is the tag.
    static const char s_cId;
};

One byte per type, whose address identifies the type.

This could be done with typeid, and the library deliberately does not do it: RTTI is often disabled in embedded products and in games, and a module that only works with RTTI enabled becomes a trap at integration. The address of a static member of a template is unique per type and is unified across translation units by the linker.

const

s_cId

Ethereal::Events::Reserved#
template< typename T > const char STypeTag< T >::s_cId = 0;
function

GetTypeId

Ethereal::Events#
template< typename T > inline TypeId GetTypeId() noexcept

The tag of type T.

scoped.hpp

#include <ethereal/cpp/event/scoped.hpp>

Scoped connection and trackable objects of the Events module.

CScopedConnection undoes a connection when it leaves scope. CTrackable undoes every connection of an object when it is destroyed. Both fight the most common bug of the observer pattern: a listener that dies while still connected.

class

CScopedConnection

Ethereal::Events#

Undoes the connection when it leaves scope. Sixteen bytes.

class CScopedConnection final

The spec calls it "the recommended default in documentation, because dangling slots are the number one bug class here". The bug is always the same: an object dies, the signal stays alive, and the next emission calls a method on memory that belongs to nobody.

It keeps the core, not the typed signal. That is what makes it fit in sixteen bytes: otherwise it would need a function pointer to know how to disconnect, and it would be twenty four.

Keeps a raw pointer. The signal has to outlive this connection. If the signal dies first, call Release before.
constructor

CScopedConnection

#
CScopedConnection() noexcept = default;

Empty connection.

constructor

CScopedConnection

#
template< typename TSignal > CScopedConnection( TSignal & Signal, const SConnection Conn ) noexcept : m_pCore( &Signal.Core() ) , m_Conn( Conn )

Takes ownership of a connection already made.

Signal
The signal the connection belongs to.
Conn
The connection.
constructor

CScopedConnection

#
CScopedConnection( CScopedConnection && Other ) noexcept : m_pCore( Other.m_pCore ) , m_Conn( Other.m_Conn )

Move constructor. The source is left empty.

operator

operator=

#
CScopedConnection & operator=( CScopedConnection && Other ) noexcept

Move assignment. Undoes the current connection first.

function

Disconnect

#
void Disconnect() noexcept

Undoes now, instead of waiting for the end of the scope.

function

Release

#
void Release() noexcept

Forgets the connection without undoing it.

Used when the signal died first: undoing it then would write to freed memory.

function

IsConnected

#
bool IsConnected() const noexcept

Holds a connection.

function

Id

#
SConnection Id() const noexcept

The connection held.

class

CTrackable

Ethereal::Events#

Inherit from this so the connections of the object die with it.

class CTrackable

The spec states the cost plainly, and it is worth repeating:

"Cost model must be stated plainly: this adds a pointer per connection and a destructor walk. It does not add cost to Emit."

And it says why it is not a 'weak_ptr':

"No 'weak_ptr'. No atomic refcount. The intrusive approach is strictly faster and the lifetime rule is explicit."

Four connections fit without touching the heap, as with the slots of a signal.

constructor

CTrackable

#
CTrackable() noexcept;

Constructor. No connection tracked.

destructor

~CTrackable

#
virtual ~CTrackable();

Undoes every connection of this object.

function

Track

#
bool Track( CSignalCore * pCore, SConnection Conn ) noexcept;

Starts tracking one more connection.

pCore
Core of the signal.
Conn
The connection.
false when there was no memory. The connection stays made, and whoever made it decides what to do about it.
function

DisconnectTracked

#
void DisconnectTracked() noexcept;

Undoes all of them, now.

function

TrackedCount

#
ETL_UINT32 TrackedCount() const noexcept;

Number of connections this object tracks.

function

ConnectTracked

Ethereal::Events#
template< auto TMemberFn, typename TObj, typename... TArgs > inline SConnection ConnectTracked( CSignal< TArgs... > & Signal, TObj * const pObj ) noexcept

signal.hpp

#include <ethereal/cpp/event/signal.hpp>

Signal core of the Events module: the connection handle and the slot list with its emission discipline.

The performance mandate of this file changes the whole design. The spec of the module starts by saying what is not accepted, by name: "An event bus is where naive implementations quietly destroy performance: 'std::function' allocations, 'shared_ptr' refcount traffic, 'std::map<type_index, ...>' lookups, and a heap allocation per emission. None of that is acceptable here."

The previous version of this module used the first two. Not by carelessness: it was a correct design, with the right reentrancy semantics, and it passed one hundred sixty four checks. But it was measured against the targets of the spec:

  • emit to zero connected: 3.79 ns (target < 2)
  • emit to one connected: 25.3 ns (target < 5)
  • emit to 100 connected: 1589.3 ns (target < 200)
  • connect four: 7 allocations (target: zero up to 4) Eight times over in the case of one hundred. That is not fixed by tuning: a 'std::function' per slot, inside a 'shared_ptr', and a copy of the 'shared_ptr' per call during emission are three indirections and a pair of atomic operations per slot, and none of them goes away without changing the design.

What this design does instead. A slot is a pair: a context pointer and a function pointer. Sixteen bytes, four per cache line. Emission is a linear walk over a contiguous vector of these pairs, with no list, no node, no virtual call and no reference counting.

The cold data lives in another vector. The generation and the priority are needed on connect and disconnect, never on emit. Mixing them in the same record would put twenty four bytes per slot on the cache line of the hot walk, two and a half per line instead of four. There are two parallel vectors, and the hot one only has what emission reads.

Emitting to nobody is one read and one branch. The count is here in the header, visible to the compiler, with no call to cross. The spec asks for "a single predictable branch", and that is it literally.

The call list and the 'std::function' that does not exist: "No 'std::function'. Callbacks are stored as raw context plus erased function pointer. A capturing lambda connects by binding to a caller-owned object, and the API makes the lifetime requirement explicit in the name." That is why CSignal::ConnectBorrowed has that name and not 'Connect': it does not copy what it receives, it keeps the address. Passing it a temporary leaves a dangling pointer, and the name exists so nobody does it without reading.

struct

SConnection

Ethereal::Events#
C++
struct   SConnection   final
{
    /// @brief  Slot index, 0xFFFFFFFF when the connection never existed.
    ETL_UINT32    uIndex = 0xFFFFFFFFu;

    /// @brief  Generation of the slot when it was connected.
    ETL_UINT32    uGeneration = 0;


    /// @brief  This connection did exist.
    ///
    ETL_API_NOIGN    bool IsValid() const ETL_NOEXCEPT
    {
        return uIndex != 0xFFFFFFFFu;
    }
};

What is kept to disconnect later. An eight byte POD.

Disconnecting is O(1), never a scan. The index says where, and the generation says whether that slot is still the same one as when it was connected.

Without the generation, an id kept after its slot was reused would disconnect someone else's, and that bug does not show up where it was made: it shows up as a listener that "stopped receiving".

operator

operator==

Ethereal::Events#
inline bool operator==( const SConnection & A, const SConnection & B ) noexcept

The two connections are the same.

operator

operator!=

Ethereal::Events#
inline bool operator!=( const SConnection & A, const SConnection & B ) noexcept

The two connections are different.

const

ETL_SIGNAL_INLINE_SLOTS

Ethereal::Events#
constexpr ETL_UINT32 ETL_SIGNAL_INLINE_SLOTS = 4u;

How many slots fit without touching the heap.

The spec sets four: "Most signals have one or two listeners and must never touch the heap."

class

CSignalCore

Ethereal::Events#

The slot list and the emission discipline, without knowing their signature.

class CSignalCore

The logic that does not depend on the type is compiled once inside the library. The template on top only converts function pointers. Without this, each signal signature used in the project would duplicate the same list, the same depth count and the same compaction.

But the members are here, not behind a pointer. Emitting to nobody has to be one read and one branch, and that requires the compiler to see the count. A 'unique_ptr< SImpl >' would put an indirection on the path the spec wants to be the cheapest of all.

alias

void

#
using GenericFn = void ( * )();

A function pointer without a signature.

Converting a function pointer to another function pointer type and back is defined by the standard. Calling through the wrong type is not. The template on top is the only one that converts, and it knows the signature.

struct

SHot

#
C++
struct   SHot
{
    /// @brief  Context passed back on each call.
    void *        pContext;

    /// @brief  The function, null for a dead slot (tombstone).
    GenericFn    pfn;
};

The slot as emission sees it. Sixteen bytes and nothing else.

struct

SCold

#
C++
struct   SCold
{
    /// @brief  Generation of the slot.
    ETL_UINT32    uGeneration;

    /// @brief  Priority, lower comes first.
    ETL_INT32    iPriority;
};

What only connect and disconnect read.

constructor

CSignalCore

#
CSignalCore() noexcept;

Constructor. The slots start in the inline storage.

function

SlotSpan

#
ETL_UINT32 SlotSpan() const noexcept

Number of slots, live and dead.

function

IsEmptyFast

#
bool IsEmptyFast() const noexcept

The fast guard: nobody is listening.

function

Hot

#
const SHot * Hot() const noexcept

The hot vector. Contiguous, and the emission walks over it.

function

BeginEmit

#
ETL_UINT32 BeginEmit() noexcept

Enters an emission and freezes the number of slots.

Slots added during the emission are not called in that pass. The spec asks for this to be documented exactly: "The emission loop caches SlotCount at entry so slots added during emission are not called in that pass. Document this precisely, it is an observable semantic."

It is inline on purpose. Measured: with it and its sibling out of line, emitting to one connected slot cost 4.5 to 5.5 ns, right on the target of five and oscillating around it. That is two calls per emission on a path the spec wants indistinguishable from a jump.

How many indices to walk.
function

EndEmit

#
void EndEmit() noexcept

Leaves the emission. On the outermost one, applies what was deferred.

The common case is nothing deferred, and then this is one decrement and one branch. The real work is in ApplyDeferred, which stays out of line because it almost never runs.

function

IsEmitting

#
bool IsEmitting() const noexcept

An emission is running on this stack.

struct

SEmitScope

#
C++
struct   SEmitScope   final
{
    /// @brief  The core of the emission.
    CSignalCore &        rCore;

    /// @brief  How many indices to walk, frozen on entry.
    const ETL_UINT32    uCount;


    /// @brief  Enters the emission.
    ///
    explicit SEmitScope( CSignalCore & rC ) ETL_NOEXCEPT
        : rCore( rC ), uCount( rC.BeginEmit() ) {}

    /// @brief  Leaves the emission, and applies what was deferred on the outermost one.
    ///
    ~SEmitScope()        { rCore.EndEmit(); }

    SEmitScope( const SEmitScope & ) = delete;
    SEmitScope & operator=( const SEmitScope & ) = delete;
};

One emission as a scope: BeginEmit on entry, EndEmit on exit.

The depth goes back down also when a slot throws. Until 11-10-2026 every emission called the pair by hand, and an exception left the depth marked forever: every connect made afterwards was deferred to the end of an emission that never came.

Inline, like the pair. The normal path is the same two inline calls.

function

Add

#
SConnection Add( void * pContext, GenericFn pfn, ETL_INT32 iPriority, bool bPriority );

Adds a slot.

pContext
The context, passed back on each call.
pfn
The function. Null is refused.
iPriority
Lower comes first. See UsesPriority.
bPriority
false keeps the connection order and sorts nothing.
The connection, invalid on failure.
function

Remove

#
bool Remove( SConnection Conn ) noexcept;

Undoes a connection. O(1).

function

RemoveAll

#
void RemoveAll() noexcept;

Undoes all of them.

function

LiveCount

#
ETL_UINT32 LiveCount() const noexcept;

Number of live slots.

function

Compact

#
void Compact() noexcept;

Collects the tombstones. Cannot run during an emission.

It moves the live slots down, so the indices already handed out stop pointing where they pointed. The SConnection is a copy in the hands of the caller, and nobody updates it.

What it cannot do is lose the link. If a CScopedConnection could no longer disconnect because of this, its slot would stay alive pointing to a dead object, and the next emission would call it. That is why Remove searches by generation when the index does not match, and only after a compaction happened.

The cost is declared: after a compaction, a Remove that misses the index costs a pass over the vector. The spec forbids scanning to disconnect, and what it forbids is the normal case. This one only happens to whoever asked for the compaction.

function

DeadCount

#
ETL_UINT32 DeadCount() const noexcept

Number of tombstones waiting to be collected.

Without this, 'Compact' is a guess. It costs a pass over the vector and cannot run during an emission. Whoever calls it now and then "to be safe" pays without knowing whether there was anything to collect. Whoever never calls it lets the vector grow with holes. This number answers the question.

It is also what makes the compaction observable. Compact returns void and moves slots under the caller. Without a number that changes, a bench cannot tell a compaction that ran from one that gave up at the start.

function

UsesPriority

#
bool UsesPriority() const noexcept

Some connection asked for priority.

While nobody asks, no sort ever runs and the vector stays in connection order.

function

ContextAt

#
void * ContextAt( ETL_UINT32 uIndex ) const noexcept;

The context of the slot at this index, for whoever needs to compare it.

signal_t.hpp

#include <ethereal/cpp/event/signal_t.hpp>

Typed signals of the Events module: CSignal and CSignalR.

Thin templates over CSignalCore. They only convert function pointers, the list logic is compiled once in the library. Read the performance mandate at the top of 'signal.hpp' before changing anything here.

class

CSignal

Ethereal::Events#

A call list with a fixed signature, notified in connection order.

template< typename... TArgs > class CSignal

Read the performance mandate at the top of signal.hpp before changing anything. Nothing here is a matter of style.

C++
Ethereal::Events::CSignal< int > OnSomething;

struct SListener { int iSum = 0; };

SListener Mine;

const auto C = OnSomething.Connect( &Mine, []( void * p, int i )
{
    static_cast< SListener * >( p )->iSum += i;
} );

OnSomething.Emit( 7 );

OnSomething.Disconnect( C );
alias

void

#
using SlotFn = void ( * )( void *, TArgs... );

The signature of a slot: context first, then the arguments.

constructor

CSignal

#
CSignal() = default;

Default constructor. No slots, no allocation.

function

Connect

#
SConnection Connect( void * const pContext, const SlotFn pfn ) noexcept

Connects a free function with a context.

The context belongs to the caller and has to outlive the connection. See CScopedConnection and CTrackable to tie the two lifetimes.

pContext
Passed back on each call.
pfn
The function.
The connection, invalid on failure.
function

ConnectWithPriority

#
SConnection ConnectWithPriority( void * const pContext, const SlotFn pfn, const ETL_INT32 iPriority ) noexcept

Connects with a priority. Lower comes first.

While nobody calls this, no sort ever runs and the vector stays in connection order. That is what the spec asks: "When unused, the array stays in connect order and no sort ever runs."

pContext
Passed back on each call.
pfn
The function.
iPriority
The priority.
The connection, invalid on failure.
function

Connect

#
template< auto TMemberFn, typename TObj > SConnection Connect( TObj * const pObj ) noexcept

Connects a method of an object, at no extra cost.

The method pointer is a template constant, so the indirection goes away at compile time: what is stored is a free function pointer that does the 'static_cast' and calls.

C++
OnSomething.Connect< &SListener::Receive >( &Mine );
pObj
The object.
The connection, invalid on failure.
function

ConnectBorrowed

#
template< typename TCallable > SConnection ConnectBorrowed( TCallable & Callable ) noexcept

Connects a callable object of the caller, keeping its address.

The name says "borrowed" on purpose. This does not copy what it receives, it keeps the address. Passing it a temporary (a lambda written in the call itself) leaves a dangling pointer that fires on the next emission.

The spec is explicit about it: "A capturing lambda connects by binding to a caller-owned object, and the API makes the lifetime requirement explicit in the name."

C++
auto Fn = [ & ]( int i ) { iSum += i; };        // lives in the caller

OnSomething.ConnectBorrowed( Fn );
Callable
The callable. Has to outlive the connection.
The connection, invalid on failure.
function

Disconnect

#
bool Disconnect( const SConnection Conn ) noexcept

Undoes a connection. O(1), never a scan.

function

DisconnectAll

#
void DisconnectAll() noexcept

Undoes all of them.

function

Compact

#
void Compact() noexcept

Collects the tombstones.

function

DeadCount

#
std::size_t DeadCount() const noexcept

Number of tombstones waiting to be collected. See the note on the core.

function

Emit

#
void Emit( TArgs... Args ) const

Calls every connected slot, in order.

Slots connected during the emission are not called in this pass, and that is observable semantics, not a detail. The count is frozen on entry.

function

SlotCount

#
std::size_t SlotCount() const noexcept

Number of live slots.

function

IsEmpty

#
bool IsEmpty() const noexcept

No live slot.

function

IsEmitting

#
bool IsEmitting() const noexcept

An emission is running.

function

Core

#
CSignalCore & Core() noexcept

The core, for whoever needs it. Not an API for common use.

class

CSignalR

Ethereal::Events#

A signal whose slots return something.

template< typename TResult, typename... TArgs > class CSignalR

The spec calls it "result aggregation", and the case that matters is the veto: a chain of handlers where the first one that says "handled" stops the chain. See EmitUntilTrue.

alias

TResult

#
using SlotFn = TResult ( * )( void *, TArgs... );

The signature of a slot: context first, then the arguments.

constructor

CSignalR

#
CSignalR() = default;

Default constructor. No slots, no allocation.

function

Connect

#
SConnection Connect( void * const pContext, const SlotFn pfn ) noexcept

Connects a free function with a context.

function

Disconnect

#
bool Disconnect( const SConnection Conn ) noexcept

Undoes a connection. O(1).

function

DisconnectAll

#
void DisconnectAll() noexcept

Undoes all of them.

function

EmitFirst

#
TResult EmitFirst( TArgs... Args ) const

Calls the first live slot and stops there.

Its result, or TResult() when there is none.
function

EmitLast

#
TResult EmitLast( TArgs... Args ) const

Calls all of them and returns the result of the last live one.

The last result, or TResult() when there is none.
function

EmitUntilTrue

#
bool EmitUntilTrue( TArgs... Args ) const

Calls until one returns true. The veto chain.

true when some slot handled it.
function

EmitCollect

#
void EmitCollect( TResult * const pOut, const std::size_t uCapacity, std::size_t * const pCount, TArgs... Args ) const

Calls all of them and writes the results into the buffer of the caller.

It does not return a container, and the spec is explicit: "EmitCollect writes into a caller span. It does not return a container." Returning a vector would put a heap allocation on every emission.

When there are more results than fit, the extra ones are discarded and pCount says how many fit. The slots are called anyway, because not calling them would change what they do.

pOut
Where to write. May be null if uCapacity is zero.
uCapacity
How many fit.
pCount
Receives how many were written. May be null.
function

SlotCount

#
std::size_t SlotCount() const noexcept

Number of live slots.

function

IsEmpty

#
bool IsEmpty() const noexcept

No live slot.