Overview / System & concurrency

coroutine

Fibers with assembly context switching and an M:N work-stealing scheduler, with groups, cancellation, fiber synchronization and channels.

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

coroutine_inc.hpp

#include <ethereal/cpp/coroutine/coroutine_inc.hpp>

Umbrella header of the Coroutine module.

Includes the whole module: the shared types, the fiber and its stack pool, the scheduler, the wait primitives and the channels.

The bridge to the C++20 coroutines is not included here. It lives in 'cpp20.hpp', a separate header that is never needed to build. The spec requires the module to build and be fully functional in C++17 without it.

channel.hpp

#include <ethereal/cpp/coroutine/channel.hpp>

Channels between fibers.

A fixed capacity ring with two wait lists: senders that do not fit and receivers with nothing to take. Both suspend the fiber.

One lock for everything, on purpose. The ring and the two lists must move together: publishing an element and waking its receiver are one operation. With separate locks there would be an instant where the message was there and nobody had been told, and if the one told had already given up, the message would be left without an owner. The lock is a spin lock because it protects a handful of writes.

Capacity zero is a rendezvous. There is nowhere to store a value, so a send only goes through if a receiver is already waiting. Otherwise the sender suspends until one arrives. The send returns when a receiver is committed to take the value, not when it has read it. The second would cost one more context switch per message. Whoever needs it uses an acknowledgement channel in the other direction, which is explicit and costs the same.

Close discards nothing: pending receivers drain, then fail. What is already in the ring is still delivered, and 'Receive' returns 'eClosed' only when the ring is empty. A send after Close fails right away. Closing means "nothing more is coming", and a channel that dropped what it had accepted would lose work the sender considered delivered.

class

CChannel

Ethereal::Coroutine#

A queue between fibers, with waiting on both sides.

template< typename T > class CChannel final

T must be movable without throwing. The channel moves elements with the spin lock held, and an exception there would leave the lock taken forever, in a module that does not even use exceptions.

constructor

CChannel

#
CChannel() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( const std::size_t uCapacity )

Allocates the ring and opens the channel.

uCapacity
Capacity. Zero is a rendezvous.
eOk, or eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Close

#
void Close()

Says nothing more is coming. What is already there is still delivered.

function

IsClosed

#
bool IsClosed() const noexcept

true after Close.

function

Size

#
std::size_t Size() noexcept

Number of elements in the ring.

function

Capacity

#
std::size_t Capacity() const noexcept

Capacity given to Init.

function

TrySend

#
EStatus TrySend( const T & Value )

Sends if there is room. Never waits.

Value
Value to send.
eOk, eWouldBlock, eClosed or eNotInitialized.
function

TryReceive

#
EStatus TryReceive( T * const pOut )

Receives if there is an element. Never waits.

pOut
Receives the element. May be null to discard it.
eOk, eWouldBlock, eClosed or eNotInitialized.
function

Send

#
EStatus Send( const T & Value, const CDeadline Deadline = CDeadline::Never() )

Sends, waiting for room.

Value
Value to send.
Deadline
Until when to wait.
eOk, eClosed, eTimeout, eNotOnFiber or eNotInitialized.
function

Receive

#
EStatus Receive( T * const pOut, const CDeadline Deadline = CDeadline::Never() )

Receives, waiting for an element.

pOut
Receives the element. May be null to discard it.
Deadline
Until when to wait.
eOk, eClosed, eTimeout, eNotOnFiber or eNotInitialized.

coroutine_types.hpp

#include <ethereal/cpp/coroutine/coroutine_types.hpp>

Shared types of the Coroutine module.

Status codes, the clock, the deadline, cooperative cancellation and the creation parameters of fibers and schedulers.

The module exists because a context switch is much cheaper than a thread switch. If it is not, the module has no reason to exist. That drives the design:

  • The switch is hand written assembly, one per ABI. Not 'ucontext' (one kernel call per switch), not 'setjmp' (no guaranteed semantics), not Win32 fibers (they save more than needed and only exist on Windows).
  • Stacks come from a pool with a free list. Reserving a stack per task costs more than a thousand switches.
  • The control block lives at the top of its own stack, so spawning a task allocates nothing and the block is on the cache line the fiber touches next.
  • No 'std::function'. A task body is a function pointer plus a context. The C++20 bridge is a separate header.
enum

EStatus

Ethereal::Coroutine#
C++
enum class   EStatus : ETL_UINT8
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  Not started yet, or the start failed.
    eNotInitialized,

    /// @brief  No memory for the stack, or the pool ran out.
    eOutOfMemory,

    /// @brief  A parameter makes no sense.
    eInvalidArgument,

    /// @brief  The deadline passed.
    eTimeout,

    /// @brief  Cancelled. See @ref SCancelToken.
    eCancelled,

    /// @brief  The channel was closed.
    eClosed,

    /// @brief  Not possible right now. Returned by the 'Try*' variants.
    eWouldBlock,

    /// @brief  Shutting down, nothing new is accepted.
    eShuttingDown,

    /// @brief  Called from a place where no fiber is running.
    eNotOnFiber,

    /// @brief  The stack overflowed. See the guard page.
    eStackOverflow,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///          ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed,

    /// @brief  Old British spelling of eNotInitialized, same value. Will be removed.
    eNotInitialised [[deprecated( "use EStatus::eNotInitialized" )]] = eNotInitialized
};

Result of an operation.

function

StatusName

Ethereal::Coroutine#
const ETL_CHAR * StatusName( EStatus eStatus ) noexcept;

Short text name of a status.

eStatus
The status.
A static string, "unknown" for an unknown value.
function

CheckLicense

Ethereal::Coroutine#
EStatus CheckLicense() noexcept;

Says whether a coroutine object may start.

Called by CChannel::Init, whose body lives in the header. Paid once per Init, never on a Send or a Receive.

eOk, or eNotLicensed when the library is not licensed.
class

IClock

Ethereal::Coroutine#

Source of time.

class IClock
destructor

~IClock

#
virtual ~IClock() = default;

Destructor.

function

NowNs

#
virtual ETL_UINT64 NowNs() const noexcept = 0;

Current time, in nanoseconds.

function

SystemClock

Ethereal::Coroutine#
IClock & SystemClock() noexcept;
class

CManualClock

Ethereal::Coroutine#

A clock that only moves when told to. For tests.

class CManualClock final : public IClock
function

NowNs

#
ETL_UINT64 NowNs() const noexcept override

Current time, in nanoseconds.

function

AdvanceMs

#
void AdvanceMs( const ETL_UINT64 uMs ) noexcept

Moves the clock forward.

uMs
Milliseconds to advance.
struct

CDeadline

Ethereal::Coroutine#
C++
struct   CDeadline   final
{
    /// @brief  Deadline in clock nanoseconds. Zero means no deadline.
    ETL_UINT64        uWhenNs = 0u;


    /// @brief  No deadline: waits as long as needed.
    ///
    ETL_API_NOIGN    static CDeadline Never() ETL_NOEXCEPT        { return CDeadline{ 0u }; }


    /// @brief  Already expired: does not wait at all.
    ///
    ETL_API_NOIGN    static CDeadline Expired() ETL_NOEXCEPT            { return CDeadline{ 1u }; }


    ///
    /// FromNowMs
    ///
    /// @brief  Deadline a number of milliseconds from now.
    ///
    /// @param uMs        Milliseconds from now.
    /// @param Clock    Clock to read.
    ///
    /// @return  The deadline. Never zero.
    ///
    ETL_API_NOIGN    static CDeadline FromNowMs( const ETL_UINT64 uMs,
                                               IClock & Clock ) ETL_NOEXCEPT
    {
        const ETL_UINT64 uWhen = Clock.NowNs() + ( uMs * 1000000ull );

        /// Zero means no deadline. A deadline that landed on zero would never expire.
        return CDeadline{ ( uWhen != 0u ) ? uWhen : 1u };
    }


    ///
    /// Passou
    ///
    /// @brief  Checks whether the deadline has passed.
    ///
    /// @param Clock    Clock to read.
    ///
    /// @return  true when passed. Always false without a deadline.
    ///
    ETL_API_NOIGN    bool HasPassed( IClock & Clock ) const ETL_NOEXCEPT
    {
        if( uWhenNs == 0u )
            return false;

        return Clock.NowNs() >= uWhenNs;
    }
};

Until when to wait.

An instant, not a duration. A wait that repeats with a duration starts counting again on every round, and a 10 ms wait that wakes up fifty times for another reason waits half a second without anyone noticing.

struct

SCancelSource

Ethereal::Coroutine#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_CLASS_ALIGN   SCancelSource   final
{
    /// @brief  Raised when the group is cancelled.
    std::atomic< bool >        bCancelled{ false };

    /// @brief  Source of the parent group. A cancellation goes down the tree through it.
    SCancelSource *            pParent = nullptr;
};

Cancellation flag shared by a group.

struct

SCancelToken

Ethereal::Coroutine#
C++
ETL_END_INTENDED_PADDING


/// @brief  The side that gets cancelled. Copyable, owns nothing.
///
struct   SCancelToken   final
{
    /// @brief  Source this token reads. Null means never cancelled.
    SCancelSource *        pSource = nullptr;


    /// @brief  Checks this source and all its parents.
    ///
    ETL_API_NOIGN    bool IsCancelled() const ETL_NOEXCEPT
    {
        const SCancelSource * p = pSource;

        /// Loop : Walks up the tree. A cancelled group cancels everything below it.
        while( p != nullptr )
        {
            if( p->bCancelled.load( std::memory_order_relaxed ) )
                return true;

            p = p->pParent;
        }

        return false;
    }
};
struct

SFiberParams

Ethereal::Coroutine#
C++
struct   SFiberParams   final
{
    /// @brief  'sizeof( SFiberParams )'. Lets fields be added without breaking
    ///             callers that are already compiled.
    ETL_UINT32        uStructSize = static_cast< ETL_UINT32 >( sizeof( SFiberParams ) );

    /// @brief  Stack size, rounded up to whole pages.
    std::size_t        uStackSize = 64u * 1024u;

    /// @brief  A page with no access at the bottom of the stack.
    ///
    /// @details  Turn it off and an overflow silently corrupts the heap instead
    ///            of giving a fault that can be diagnosed. The only reason to turn
    ///            it off is having hundreds of thousands of live fibers, where each
    ///            guard costs one page table entry.
    bool            bGuardPage = true;

    /// @brief  Context passed to the entry point.
    void *            pContext = nullptr;

    /// @brief  Entry point of the fiber.
    void            ( * pEntry )( void * pCtx ) = nullptr;
};

How a fiber is created.

struct

SSchedulerParams

Ethereal::Coroutine#
C++
struct   SSchedulerParams   final
{
    /// @brief  'sizeof( SSchedulerParams )'.
    ETL_UINT32        uStructSize = static_cast< ETL_UINT32 >( sizeof( SSchedulerParams ) );

    /// @brief  Number of workers. Zero uses the number of cores.
    ETL_UINT32        uWorkers = 0u;

    /// @brief  Stacks built ahead of time in the pool.
    std::size_t        uStackPool = 256u;

    /// @brief  Stack size of each task.
    std::size_t        uStackSize = 64u * 1024u;

    /// @brief  Guard page at the bottom of each stack.
    bool            bGuardPage = true;

    /// @brief  Steal attempts before parking.
    ///
    /// @details  Neither zero nor infinite works. Zero parks a worker at the
    ///            first empty queue and misses work that arrives right after.
    ///            Infinite has eight workers burning eight cores doing nothing.
    ETL_UINT32        uStealAttempts = 4u;

    /// @brief  Clock. Null uses SystemClock.
    IClock *        pClock = nullptr;
};

How the scheduler is built.

struct

STaskHandle

Ethereal::Coroutine#
C++
struct   STaskHandle   final
{
    /// @brief  Control block of the task.
    void *            pFiber = nullptr;

    /// @brief  Generation of the stack when the task was spawned.
    ETL_UINT64        uGeneration = 0u;
};

What is kept of a spawned task.

struct

SSchedulerStats

Ethereal::Coroutine#
C++
struct   SSchedulerStats   final
{
    /// @brief  Tasks spawned.
    ETL_UINT64    uSpawned = 0;

    /// @brief  Tasks finished.
    ETL_UINT64    uCompleted = 0;

    /// @brief  Context switches into tasks.
    ETL_UINT64    uSwitches = 0;

    /// @brief  Successful steals.
    ETL_UINT64    uSteals = 0;

    /// @brief  Failed steal attempts.
    ETL_UINT64    uStealFailures = 0;

    /// @brief  Times a worker parked.
    ETL_UINT64    uParks = 0;

    /// @brief  Spawns served by the stack pool.
    ETL_UINT64    uStackPoolHits = 0;

    /// @brief  Spawns that had to build a new stack.
    ETL_UINT64    uStackPoolMisses = 0;

    /// @brief  Tasks not finished yet.
    ETL_UINT64    uLiveFibers = 0;
};

Scheduler counters.

fiber.hpp

#include <ethereal/cpp/coroutine/fiber.hpp>

Fibers, the stack pool and fiber local storage.

The context switch is assembly, one file per ABI. The control block of a fiber lives at the top of its own stack, and stacks come from a pool with an intrusive free list.

A fiber can resume on another worker thread. Fiber local storage travels with the fiber, a 'thread_local' does not.

function

EtlFiberSwitch

Ethereal::Coroutine#
void EtlFiberSwitch( void ** ppFromSp, void * pToSp );

Saves the current context and jumps to another one.

ppFromSp
Receives the stack pointer of the current context.
pToSp
Stack pointer of the context to resume.
function

EtlFiberTrampolineAddress

Ethereal::Coroutine#
void * EtlFiberTrampolineAddress( void );

Address of the trampoline, for the code that builds the initial frame.

enum

EFiberState

Ethereal::Coroutine#
C++
enum class   EFiberState : ETL_UINT8
{
    /// @brief  Built, with the initial frame in place, and not run yet.
    eFresh = 0,

    /// @brief  Running right now.
    eRunning,

    /// @brief  Suspended, with its context saved.
    eSuspended,

    /// @brief  The entry point returned.
    eDone
};

Stage of the life of a fiber.

enum

EYieldWish

Ethereal::Coroutine#
C++
enum class   EYieldWish : ETL_UINT8
{
    /// @brief  Back to the run queue right away. This is 'Yield'.
    eRequeue = 0,

    /// @brief  Out until someone puts it back. Every wait uses this.
    eParked,

    /// @brief  Back to the queue when the clock passes 'uWakeNs'.
    eSleep,

    /// @brief  Finished.
    eFinished
};

What a fiber wants to happen after it gives up the processor.

const

kMaxFlsSlots

Ethereal::Coroutine#
inline constexpr ETL_UINT32 kMaxFlsSlots = 16u;

Number of fiber local storage slots.

Fixed, and embedded in the control block. A table per fiber would cost an allocation per fiber, which is what this module exists to avoid.

struct

SFiberControl

Ethereal::Coroutine#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_CLASS_ALIGN   SFiberControl   final
{
    ///--- What the switch touches, first ---------------------------------

    /// @brief  Saved stack pointer, while the fiber is not running.
    void *            pSp = nullptr;

    /// @brief  Stack pointer of the context that resumed it. 'Yield' returns there.
    void *            pResumerSp = nullptr;

    ///--- Identity --------------------------------------------------------

    /// @brief  Entry point.
    void            ( * pEntry )( void * pCtx ) = nullptr;

    /// @brief  Context passed to the entry point.
    void *            pContext = nullptr;

    ///--- Memory ----------------------------------------------------------

    /// @brief  Base of the reservation, guard included. This is what gets freed.
    void *            pAllocBase = nullptr;

    /// @brief  Size of the reservation, in bytes.
    std::size_t        uAllocSize = 0u;

    /// @brief  Usable bottom of the stack, right above the guard.
    void *            pLimit = nullptr;

    /// @brief  Top of the stack, where this block lives.
    void *            pTop = nullptr;

    ///--- State -----------------------------------------------------------

    /// @brief  Stage of the life of the fiber.
    EFiberState        eState = EFiberState::eFresh;

    /// @brief  true when the stack has a guard page.
    bool            bHasGuard = false;

    /// @brief  Incremented on every reuse of the stack. Catches a stale handle.
    ETL_UINT64        uGeneration = 0u;

    ///--- Set by the scheduler --------------------------------------------

    /// @brief  Scheduler that owns the fiber.
    void *            pOwner = nullptr;

    /// @brief  Context that resumed it. 'Yield' returns to its context.
    SFiberControl *    pResumer = nullptr;

    /// @brief  What the fiber wants the scheduler to do when it yields.
    ///
    /// @details  Without it the worker cannot tell a fiber that yielded and
    ///            wants to run again from one waiting on a channel. A waiting
    ///            fiber put back in the queue would spin forever on a core.
    ///
    ///            The values are those of @ref EYieldWish.
    ETL_UINT8        uWish = 0;

    /// @brief  When to wake up, in clock nanoseconds. Zero is no alarm.
    ETL_UINT64        uWakeNs = 0;

    /// @brief  Completion hook, called when the fiber finishes.
    ///
    /// @details  A group needs to know when a child finishes. Wrapping the user
    ///            body in a record with the group pointer would cost one
    ///            allocation per child, and the spec requires zero allocations
    ///            to spawn a task once the pool is warm.
    ///
    ///            The hook lives in the control block, which already exists. It
    ///            runs on the worker, after the fiber finishes and before the
    ///            stack goes back to the pool. It never runs inside the fiber,
    ///            whose stack is about to be recycled.
    void            ( * pOnFinish )( void * pCtx, SFiberControl * pFiber ) = nullptr;

    /// @brief  Context passed to the completion hook.
    void *            pOnFinishCtx = nullptr;

    /// @brief  Called by the worker after the fiber is off the processor.
    ///
    /// @details  Every wait has the same shape: join a list, release the lock
    ///            that protects the list, and park. Between releasing the lock
    ///            and parking there is a window where another thread can take
    ///            the fiber from the list and run it while it is still running
    ///            here. The same stack on two processors.
    ///
    ///            So the lock is released by the worker, after the switch. The
    ///            fiber only becomes visible to whoever can wake it when it is
    ///            no longer running anywhere. Same design as 'gopark' in Go, for
    ///            the same reason.
    void            ( * pAfterPark )( void * pCtx ) = nullptr;

    /// @brief  Context passed to pAfterPark.
    void *            pAfterParkCtx = nullptr;

    /// @brief  Link of the wait list this fiber is in, if any.
    SFiberControl *    pNextWaiter = nullptr;

    /// @brief  Wake guard. Only the waker that changes it from 0 to 1 queues the fiber.
    ///
    /// @details  A wait with a deadline has two alarms: the signal it waits for
    ///            and the clock. Both can fire at the same time, and if both
    ///            queued the fiber it would run twice, the same stack in
    ///            parallel. The one that loses the exchange does nothing.
    std::atomic< ETL_UINT32 >    uWoken{ 0 };

    /// @brief  Next fiber in the free list of the stack pool.
    void *            pNextFree = nullptr;

    /// @brief  Cancellation token of the task.
    SCancelToken    Cancellation;

    /// @brief  Fiber local storage. One indirection from the current pointer.
    void *            pFls[ kMaxFlsSlots ] = {};

    /// @brief  The fiber as seen by ThreadSanitizer. Null outside a TSan build.
    ///
    /// @details  TSan keeps a shadow stack per thread. A context switch it does
    ///            not see leaves it wrong, and a fiber moving to another thread
    ///            crashed it (SEGV inside TSan in the 'coroutine' test,
    ///            2026-09-28). Switches are announced to it
    ///            ('__tsan_switch_to_fiber') and this is what it returns. Always
    ///            present, so the layout is the same with and without TSan.
    void *            pTsanFiber = nullptr;
};

Control block of a fiber.

Embedded at the top of its own stack, for two reasons:

  • Spawning a task allocates nothing. The stack is already reserved and the block is inside it. An allocation costs more than a thousand context switches.
  • It is on the right cache line. Whoever touches the block is about to touch the stack, and the other way around.
function

CurrentFiber

Ethereal::Coroutine#
SFiberControl * CurrentFiber() noexcept;
function

FlsAlloc

Ethereal::Coroutine#
ETL_UINT32 FlsAlloc() noexcept;

Reserves a fiber local storage slot. Call once, at startup.

The slot, or 'kMaxFlsSlots' when there are no slots left.
function

FlsGet

Ethereal::Coroutine#
void * FlsGet( const ETL_UINT32 uSlot ) noexcept

Reads a slot of the current fiber. One indirection.

uSlot
Slot returned by FlsAlloc.
The value, or nullptr outside a fiber or with an invalid slot.
function

FlsSet

Ethereal::Coroutine#
bool FlsSet( const ETL_UINT32 uSlot, void * const pValue ) noexcept

Writes a slot of the current fiber.

uSlot
Slot returned by FlsAlloc.
pValue
Value to store.
false outside a fiber or with an invalid slot.
class

CStackPool

Ethereal::Coroutine#

Pool of fiber stacks.

class CStackPool final
constructor

CStackPool

#
CStackPool() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( std::size_t uCount, std::size_t uStackSize, bool bGuardPage ) noexcept;

Builds the stacks ahead of time.

The kernel calls are paid here, all at once and off the hot path.

uCount
Number of stacks to build.
uStackSize
Usable size of each stack, at least 4 KB.
bGuardPage
Adds a guard page to each stack.
eOk, eInvalidArgument or eOutOfMemory. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Acquire

#
SFiberControl * Acquire() noexcept;

Takes a stack, with the control block at the top and no frame yet.

No kernel calls while the pool is warm.

function

Release

#
void Release( SFiberControl * pFiber ) noexcept;

Returns a stack to the free list. The memory is kept for the next one.

pFiber
Control block of the stack.
function

Trim

#
std::size_t Trim( std::size_t uKeep ) noexcept;

Frees the free stacks beyond a count.

A peak is not the steady state. A program that had a million tasks for a minute should not keep a million stacks forever.

uKeep
Free stacks to keep.
Number of stacks freed.
function

Live

#
std::size_t Live() const noexcept

Stacks in use.

function

Free

#
std::size_t Free() const noexcept

Stacks in the free list.

function

StackSize

#
std::size_t StackSize() const noexcept

Total size of each stack, guard included.

function

MemoryUsage

#
std::size_t MemoryUsage() const noexcept;

Bytes of virtual memory reserved by this pool.

class

CFiber

Ethereal::Coroutine#
class CFiber final
constructor

CFiber

#
CFiber() = default;

Default constructor. Call Create before use.

function

Create

#
static EStatus Create( const SFiberParams & Params, CFiber * pOut ) noexcept;

Reserves the stack and builds the initial frame. Runs nothing yet.

Params
Fiber parameters.
pOut
Receives the fiber.
eOk, eInvalidArgument or eOutOfMemory. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Resume

#
void Resume() noexcept;

Jumps into the fiber. Returns when it suspends or finishes.

function

Yield

#
static void Yield() noexcept;

Goes back to the context that resumed this fiber.

Only valid inside a fiber. From a plain thread there is nowhere to go back to, and the call does nothing.

function

IsDone

#
bool IsDone() const noexcept

true when the entry point returned, or there is no fiber.

function

Control

#
SFiberControl * Control() const noexcept

Control block of the fiber.

function

Destroy

#
void Destroy() noexcept;

Frees the stack. A suspended fiber cannot be destroyed.

Destroying a fiber halfway would drop its stack without running a single destructor, the same reason cancellation is cooperative. That case is detected and the call does nothing.

function

BuildInitialFrame

Ethereal::Coroutine#
void BuildInitialFrame( SFiberControl * pCtrl ) noexcept;
function

SwitchTo

Ethereal::Coroutine#
void SwitchTo( SFiberControl * pTarget, void ** ppSaveTo ) noexcept;

Switches to another fiber and keeps the current fiber pointer up to date.

pTarget
Fiber to run.
ppSaveTo
Receives the stack pointer of the current context.

scheduler.hpp

#include <ethereal/cpp/coroutine/scheduler.hpp>

Work stealing scheduler and task groups.

Each worker has its own lock free Chase-Lev deque. A worker with no work steals from a randomly chosen victim, and parks after a limited number of attempts.

Task groups give structured concurrency: the destructor of a group always waits for its children.

class

CChaseLev

Ethereal::Coroutine#

Double ended queue of a worker.

class CChaseLev final

The padding of this type is intended (alignment), see 'ETL_BEGIN_INTENDED_PADDING'. No ETL_CLASS_ALIGN: the members aligned to the cache line already give 64, and a smaller alignment was ignored (C4359).

constructor

CChaseLev

#
CChaseLev() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( std::size_t uCapacity ) noexcept;

Allocates the buffer.

uCapacity
Capacity, rounded up to a power of two (at least 16).
eOk or eOutOfMemory.
function

Push

#
bool Push( SFiberControl * pFiber ) noexcept;

Pushes at the bottom. Owner only.

pFiber
Fiber to push.
false when full. The caller sends it to the shared queue.
function

Pop

#
SFiberControl * Pop() noexcept;

Pops from the bottom. Owner only.

function

Steal

#
SFiberControl * Steal() noexcept;

Steals from the top. Any thread.

function

Size

#
std::size_t Size() const noexcept;

Approximate number of elements.

class

CScheduler

Ethereal::Coroutine#

Where tasks run.

class CScheduler final

The workers start in Init and stay parked until there is work. Run is not a loop: it waits until the last task finishes, and can be called from any thread.

constructor

CScheduler

#
CScheduler() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( const SSchedulerParams & Params ) noexcept;

Builds the stack pool and starts the workers.

Params
Scheduler parameters.
eOk, eInvalidArgument or eOutOfMemory. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Spawn

#
EStatus Spawn( void * pCtx, void ( * pEntry )( void * ), STaskHandle * pOut = nullptr ) noexcept;

Spawns a task. No allocations while the stack pool is warm.

pCtx
Context passed to the entry point.
pEntry
Entry point.
pOut
Receives the handle. May be null.
eOk or eOutOfMemory.
function

SpawnSuspended

#
SFiberControl * SpawnSuspended( void * pCtx, void ( * pEntry )( void * ), SCancelSource * pCancel, void ( * pOnFinish )( void * pCtx, SFiberControl * pFiber ), void * pOnFinishCtx, STaskHandle * pOut ) noexcept;

Spawns a task with everything written before it enters the queue.

The only place where a task is born, and it receives everything at once: body, context, cancellation source and completion hook. Once a fiber is in the queue any worker can take it, and writing its fields after that is a race.

Used by CTaskGroup and by whoever needs to attach things to a task.

pCtx
Context passed to the entry point.
pEntry
Entry point.
pCancel
Cancellation source. Null inherits from the spawner.
pOnFinish
Completion hook, run on the worker. May be null.
pOnFinishCtx
Context passed to the hook.
pOut
Receives the handle. May be null.
The control block, or nullptr on failure.
function

Run

#
EStatus Run() noexcept;

Waits until no task is left.

function

Shutdown

#
EStatus Shutdown( ETL_UINT64 uGraceMs ) noexcept;

Stops the scheduler.

A running task is not interrupted, that would be the forced unwind that cooperative cancellation exists to avoid. Shutdown: 1. raises the root cancellation flag, so tasks that ask know. 2. waits up to uGraceMs for the tasks to finish. 3. stops the workers.

If the grace period ends with live tasks it returns eTimeout and their stacks are not freed. Dropping the stack of a suspended fiber loses everything it had alive without running a single destructor. They stay, and their number shows in the counters.

uGraceMs
Milliseconds to wait. Zero does not wait.
eOk, eTimeout or eNotInitialized.
function

Yield

#
static void Yield() noexcept;

Gives up the processor and goes back to the queue.

function

SleepFor

#
static void SleepFor( ETL_UINT64 uMs ) noexcept;

Suspends the fiber, not the thread.

This is the difference that defines the module. A 'std::this_thread::sleep_for' inside a task stops the worker, and with it every other task in its queue. Outside a fiber this sleeps the thread. So does a standalone fiber (a CFiber with no scheduler), since nothing would wake it.

uMs
Milliseconds to sleep.
function

Current

#
static CScheduler * Current() noexcept;

Scheduler this fiber runs on, or 'nullptr'.

function

Park

#
static void Park() noexcept;

Takes the current fiber out of circulation until Ready is called with it.

The primitive of every wait: channels, semaphores, groups. The caller must already be in a wait list, or it is never woken.

function

ParkAnd

#
static void ParkAnd( void ( * pAfter )( void * pCtx ), void * pCtx ) noexcept;

Parks the fiber and only then runs pAfter.

Every wait has the same shape: join a list, release the lock that protects it, and park. Written like that, between releasing the lock and parking another thread can take the fiber from the list and run it while it is still running here. The same stack on two processors, immediate and silent corruption.

With this call the lock is released by the worker, after the switch. The fiber only becomes visible to whoever can wake it when it is no longer on any processor. Every wait of this module goes through here: mutex, semaphore, condition variable, wait group and channels.

pAfter
Called on the worker after the switch. May be null.
pCtx
Context passed to pAfter.
function

ParkUntilAnd

#
static void ParkUntilAnd( ETL_UINT64 uWhenNs, void ( * pAfter )( void * pCtx ), void * pCtx ) noexcept;

Same as ParkAnd, with a deadline: wakes on the signal or at the deadline, whichever comes first.

The two alarms compete and only one wins, see 'uWoken' in SFiberControl. Without that the fiber would be queued twice, the same stack on two processors.

uWhenNs
Deadline in clock nanoseconds. Zero has no deadline and falls back to ParkAnd.
pAfter
Called on the worker after the switch. May be null.
pCtx
Context passed to pAfter.
function

Ready

#
void Ready( SFiberControl * pFiber ) noexcept;

Puts a parked fiber back in the queue.

Can be called from any thread, including from outside the scheduler. That is how an I/O completion wakes the fiber waiting for it.

pFiber
Parked fiber.
function

RootCancel

#
SCancelSource * RootCancel() noexcept;

Root of the cancellation tree of this scheduler.

function

Stats

#
SSchedulerStats Stats() const noexcept;

Snapshot of the counters.

function

WorkerCount

#
std::size_t WorkerCount() const noexcept;

Number of workers.

function

MemoryUsage

#
std::size_t MemoryUsage() const noexcept;

Bytes reserved by the stack pool.

function

ReadyFiber

Ethereal::Coroutine#
bool ReadyFiber( SFiberControl * pFiber ) noexcept;
class

CTaskGroup

Ethereal::Coroutine#

A group of tasks that never outlives its children.

class CTaskGroup final
constructor

CTaskGroup

#
CTaskGroup() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( CScheduler & Scheduler ) noexcept;

Binds the group to a scheduler. The parent comes from the current task.

Scheduler
Scheduler the children run on.
eOk, eInvalidArgument or eOutOfMemory. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Spawn

#
EStatus Spawn( void * pCtx, void ( * pEntry )( void * ) ) noexcept;

Spawns a child task.

pCtx
Context passed to the entry point.
pEntry
Entry point.
eOk, eNotInitialized or eOutOfMemory.
function

Wait

#
EStatus Wait( CDeadline Deadline ) noexcept;

Waits for all children to finish.

Deadline
Until when to wait.
eOk, eTimeout or eNotInitialized.
function

CancelAll

#
void CancelAll() noexcept;

Raises the flag. It goes down the tree: subgroups see it.

function

Live

#
std::size_t Live() const noexcept;

Children not finished yet.

function

Token

#
SCancelToken Token() noexcept

Token to pass to the tasks of this group.

sync.hpp

#include <ethereal/cpp/coroutine/sync.hpp>

Wait primitives for fibers.

A plain 'std::mutex' inside a fiber is a documented trap. It blocks the thread, and the thread is not the task: it is the worker that was running that task and had N more in its queue. When it blocks, the N stop too.

It can be worse than slow. If the task holding the lock is in the queue of the worker that just blocked, it never runs, never releases the lock, and the worker never wakes. A deadlock between two tasks that never met.

The primitives of this file suspend the fiber. The worker leaves it and takes the next one.

They do not replace 'std::mutex' in normal code. Outside a fiber they fall back to spinning with thread yields, because there is no fiber to suspend. It works, but that is not what they are for.

class

CWaitList

Ethereal::Coroutine#

Queue of waiting fibers, intrusive, with a spin lock.

class CWaitList final

Intrusive: the link lives in the control block of the fiber, so waiting allocates no memory.

A spin lock and not a 'std::mutex': it protects three pointer writes. Taking an MSVC 'std::mutex' costs more than the work inside.

In the worst case the lock is held across one context switch. See CScheduler::ParkAnd, which releases it on the other side.

constructor

CWaitList

#
CWaitList() = default;

Default constructor.

function

Lock

#
void Lock() noexcept;

Takes the spin lock.

function

Unlock

#
void Unlock() noexcept;

Releases the spin lock.

function

Push

#
void Push( SFiberControl * pFiber ) noexcept;

Appends at the end. With the lock held.

pFiber
Fiber to append.
function

Pop

#
SFiberControl * Pop() noexcept;

Removes from the front. With the lock held. First in, first out, so nobody starves.

function

Remove

#
bool Remove( SFiberControl * pFiber ) noexcept;

Removes this fiber, wherever it is. With the lock held.

Needed by a wait with a deadline that woke up by the clock and is still in the list.

pFiber
Fiber to remove.
true when the fiber was in the list.
function

Empty

#
bool Empty() const noexcept

true when no fiber is waiting.

function

ReleaseLock

#
static void ReleaseLock( void * pList ) noexcept;

Releases the lock. Signature for CScheduler::ParkAnd.

pList
The CWaitList.
class

CFiberMutex

Ethereal::Coroutine#
class CFiberMutex final
constructor

CFiberMutex

#
CFiberMutex() = default;

Default constructor.

function

Lock

#
void Lock() noexcept;

Takes the mutex, suspending the fiber while it is taken.

function

TryLock

#
bool TryLock() noexcept;

Takes the mutex if it is free. Never waits.

function

Unlock

#
void Unlock() noexcept;

Releases the mutex and wakes one waiter.

class

CFiberLockGuard

Ethereal::Coroutine#
class CFiberLockGuard final
constructor

CFiberLockGuard

#
explicit CFiberLockGuard( CFiberMutex & M ) noexcept : m_M( M )

Takes the mutex.

class

CFiberSemaphore

Ethereal::Coroutine#

Counts permits. Suspends the fiber when there are none.

class CFiberSemaphore final
constructor

CFiberSemaphore

#
explicit CFiberSemaphore( const ETL_INT64 iInitial = 0 ) noexcept : m_iCount( iInitial )

Constructor.

iInitial
Initial number of permits.
function

Acquire

#
void Acquire() noexcept;

Takes a permit, suspending the fiber while there are none.

function

TryAcquire

#
bool TryAcquire() noexcept;

Takes a permit if there is one. Never waits.

function

Release

#
void Release( ETL_INT64 iCount = 1 ) noexcept;

Returns permits and wakes one waiter per permit.

iCount
Number of permits. Zero or less does nothing.
function

Count

#
ETL_INT64 Count() const noexcept

Current number of permits.

class

CFiberWaitGroup

Ethereal::Coroutine#
class CFiberWaitGroup final
constructor

CFiberWaitGroup

#
CFiberWaitGroup() = default;

Default constructor.

function

Add

#
void Add( ETL_INT64 iCount = 1 ) noexcept;

Adds to the count.

iCount
Amount to add.
function

Done

#
void Done() noexcept;

Subtracts one. At zero wakes all the waiters.

function

Wait

#
void Wait() noexcept;

Waits until the count reaches zero.

function

Count

#
ETL_INT64 Count() const noexcept

Current count.

class

CFiberConditionVariable

Ethereal::Coroutine#
class CFiberConditionVariable final
constructor

CFiberConditionVariable

#
CFiberConditionVariable() = default;

Default constructor.

function

Wait

#
void Wait( CFiberMutex & M ) noexcept;

Releases M, waits, and takes it again before returning.

M
Mutex held by the caller.
function

Wait

#
void Wait( CFiberMutex & M, bool ( * pPred )( void * pCtx ), void * pCtx ) noexcept;

Same, but only returns when pPred says yes.

This is the right way to use it. A notification can arrive before the wait starts, and there are wakeups with no notification. Without checking the condition the caller wakes and goes on with it false.

M
Mutex held by the caller.
pPred
Condition, called with the mutex held.
pCtx
Context passed to pPred.
function

NotifyOne

#
void NotifyOne() noexcept;

Wakes one waiter.

function

NotifyAll

#
void NotifyAll() noexcept;

Wakes all waiters.