Overview / System & concurrency

system

Console, threads and measurement of CPU, memory and disk, per process and per machine.

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

system_inc.hpp

#include <ethereal/cpp/system/system_inc.hpp>

console.hpp

#include <ethereal/cpp/system/console.hpp>
function

ConsoleAlloc

Ethereal::Console#
ETL_INT32 ConsoleAlloc( const char * WindowName = "Console", const short ConsoleWidth = 350, const short ConsoleHeight = 200 );

Allocates and shows a console with a title and size.

  • Windows: creates and shows a console window using the Win32 API.
  • Linux/macOS: stub function. The process already has stdout/stderr attached to the terminal. No additional window is created.
WindowName
Console window name/title.
ConsoleWidth
Width in columns.
ConsoleHeight
Height in lines.
0 = Success. 1 = Console already allocated. 2 = Invalid name. 3 = Failed to allocate the console. 4 = Failed to determine the console name. 5 = Not licensed (see Bundle::UnlockBundle).
function

ConsoleFree

Ethereal::Console#
ETL_INT32 ConsoleFree( void );

Releases the allocated console.

  • Windows: releases the allocated console.
  • Linux/macOS: only resets the internal state.
0 = Success. 1 = Console not allocated. 2 = Failed to release the console.

cpu.hpp

#include <ethereal/cpp/system/cpu.hpp>
function

Initialize_CPUSubSystem

Ethereal::Stats#
ETL_INT32 Initialize_CPUSubSystem( void );

Initializes the timers and the statistics subsystems.

Performs the internal initialization needed for the CPU usage calculations, for both the current process and the machine. Makes initial calls to the collection functions to set the reference values (baseline).

This function must be called before any attempt to obtain CPU statistics.

Result code: - 0 : Success - -2 : Not licensed (see Bundle::UnlockBundle) - <0 : Subsystem not initialized or internal error - >0 : Error code returned by the CPU routines
function

GetCurrentProcessCPU_Usage

Ethereal::Stats#
ETL_INT32 GetCurrentProcessCPU_Usage( ETL_DOUBLE & OutCPUVal );

Gets the CPU usage percentage of the current process.

Computes the CPU usage of the running process from the change in CPU time (kernel + user) between calls, normalizing the value by the number of available logical CPUs. ** The first call does not return a valid usage value. It is used only to initialize the internal values.

Platform specific implementation:

  • Windows: GetProcessTimes + GetSystemTimeAsFileTime
  • Linux : /proc/self/stat + clock_gettime (CLOCK_MONOTONIC)
  • macOS : task_info (TASK_THREAD_TIMES_INFO)
OutCPUVal
Output variable that receives the CPU usage percentage.
Result code: - 0 : Success (OutCPUVal valid) - -1 : Subsystem not initialized - 1 : Failed to get the process times (Windows) - 2 : First run (baseline initialized) - 3 : Invalid time delta (division by zero) - 4 : Failed to get the number of processors - 5 to 9 : Platform specific errors
This function is not thread-safe . Concurrent access may cause inconsistent reads due to the use of internal state and/or unsynchronized APIs.
function

GetCurrentMachineCPU_Usage

Ethereal::Stats#
ETL_INT32 GetCurrentMachineCPU_Usage( ETL_DOUBLE & OutCPUVal );

Gets the total CPU usage percentage of the machine.

Computes the global CPU usage of the system from the change in total time and idle time between calls. The returned value is the combined load of all processes on all cores. ** The first call does not return a valid usage value. It is used only to initialize the internal values.

Platform specific implementation:

  • Windows: GetSystemTimes
  • Linux : /proc/stat
  • macOS : host_statistics (HOST_CPU_LOAD_INFO)
OutCPUVal
Output variable that receives the CPU usage percentage.
Result code: - 0 : Success (OutCPUVal valid) - -1 : Subsystem not initialized - 1 : Failed to get the system times (Windows) - 2 : First run (baseline initialized) - 3 : Invalid time delta (division by zero) - 5 to 9 : Platform specific errors
This function is not thread-safe . Concurrent access may cause inconsistent reads due to the use of internal state and/or unsynchronized APIs.

disk.hpp

#include <ethereal/cpp/system/disk.hpp>
struct

sDiskStats

Ethereal::Stats#
C++
struct sDiskStats
{
    /// @note    ETL_UINT64 instead of ULONGLONG: both are unsigned 64 bit integers,
    ///            but ULONGLONG only exists with <windows.h> included.
    ///
    ETL_UINT64 readBytes;     /// Total bytes read from the disk
    ETL_UINT64 writeBytes;    /// Total bytes written to the disk
    ETL_UINT64 readOps;       /// Number of read operations
    ETL_UINT64 writeOps;      /// Number of write operations
};

Structure that stores disk usage statistics.

Holds accumulated counters of operations and of the volume of data read from and written to disk, in bytes and number of operations. Used to monitor storage I/O activity.

function

GetCurrentProcessDisk_Stats

Ethereal::Stats#
ETL_INT32 GetCurrentProcessDisk_Stats( sDiskStats & OutStats );

Gets the disk usage statistics of the current process.

Collects the storage I/O counters of the running process, including the volume of data read/written and the number of read and write operations.

Platform specific implementation:

  • Windows: GetProcessIoCounters
  • Linux : /proc/self/io
  • macOS : getrusage (limited values)
OutStats
Output structure that receives the disk statistics.
Result code: - 0 : Success - 1 : Failed to get the I/O counters (Windows) - 2 : Failed to access the process information (Linux)
This function is not thread-safe . Concurrent access may cause inconsistent reads due to the use of internal state and/or unsynchronized APIs.
function

GetCurrentMachineDisk_Stats

Ethereal::Stats#
ETL_INT32 GetCurrentMachineDisk_Stats( sDiskStats & OutStats );

Gets the global disk usage statistics of the machine.

Collects accumulated storage I/O counters over all devices and processes of the system. The values are the total reads and writes since system boot.

Platform specific implementation:

  • Windows: NtQuerySystemInformation (SystemPerformanceInformation)
  • Linux : /proc/diskstats (sum of all devices)
  • macOS : Not supported
OutStats
Output structure that receives the global disk statistics.
Result code: - 0 : Success - 1 : Failed to query the system statistics (Windows) - 2 : Failed to access the disk statistics (Linux) - -1 : Operation not supported on the platform (macOS)
This function is not thread-safe . Concurrent access may cause inconsistent reads due to the use of internal state and/or unsynchronized APIs.

memory.hpp

#include <ethereal/cpp/system/memory.hpp>
function

GetCurrentProcessMemory_Usage

Ethereal::Stats#
ETL_INT32 GetCurrentProcessMemory_Usage( std::size_t & OutMemoryVal );

Gets the amount of memory used by the current process.

Returns the total memory in bytes currently used by the running process, including private memory and memory committed by the operating system. Useful for real time monitoring of memory usage.

OutMemoryVal
Receives the amount of memory used by the process, in bytes.
0 on success, 1 on failure.
function

GetCurrentMachineMemory_Usage

Ethereal::Stats#
ETL_INT32 GetCurrentMachineMemory_Usage( std::size_t & OutMemoryVal );

Gets the total amount of memory used by the system.

Returns the total physical memory in use by the system at the time of the call, over all active processes. Suited for global analysis of memory consumption.

OutMemoryVal
Receives the total amount of memory used by the system, in bytes.
0 on success, 1 on failure.
function

ConvertBytesToMB

Ethereal::Stats#
ETL_DOUBLE ConvertBytesToMB( const std::size_t uBytes );

Converts a memory value in bytes to megabytes (MB).

Converts bytes directly to megabytes using base 1024, keeping the precision through floating point. Ideal for showing memory values in a readable form.

uBytes
Amount of memory in bytes.
Value converted to megabytes (MB).
function

ConvertBytesToGB

Ethereal::Stats#
ETL_DOUBLE ConvertBytesToGB( const std::size_t uBytes );

Converts a memory value in bytes to gigabytes (GB).

Converts bytes directly to gigabytes using base 1024, returning floating point for better precision. Suited for showing large volumes of memory.

uBytes
Amount of memory in bytes.
Value converted to gigabytes (GB).

monitor.hpp

#include <ethereal/cpp/system/monitor.hpp>
enum

EStatsID

Ethereal::Stats#
C++
enum EStatsID
{
    /// @brief    Only statistics of the current process/module.
    eCurrentProcess = 0,

    /// @brief    Statistics of the machine/VM/etc.
    ///
    ///            *** Includes the current process/module.
    ///
    eGlobal,

    /// @brief    Array-only (only for internal checks, never use it)
    eLast
};

Statistics identification.

struct

SStats

Ethereal::Stats#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SStats    final
{
    /// @brief    Last collected value.
    ///
    ETL_DOUBLE dLastValue;

    /// @brief    Minimum and maximum collected values.
    ///
    ETL_DOUBLE dMinValue;
    ETL_DOUBLE dMaxValue;

    /// @brief    Accumulated sum.
    ///
    ETL_DOUBLE dSum;

    /// @brief    Delta : Difference from the last collection.
    ///
    ETL_DOUBLE dDelta;

    /// @brief    Count of calculations/samples.
    ///
    std::uint64_t iCount;

    /// @brief    Default constructor.
    ///
    SStats();
};

Structure that stores accumulated statistical data. Holds the current, minimum and maximum value, the total sum, the delta between reads and the number of samples. Used by the manager for CPU, memory and disk.

class

CStatsManager

Ethereal::Stats#
class CStatsManager final
function

Instance

#
static CStatsManager & Instance() noexcept;

Gets the singleton instance of the statistics manager.

Reference to the single instance of CStatsManager.
function

Initialize

#
void Initialize( const bool bEnableCPU, const bool bEnableMemory, const bool bEnableDisk, const ETL_DOUBLE dMinTimeStampToGenerateStats = 0.6 );

Initializes the statistics manager. Sets which monitors are active (CPU, memory and disk) and the minimum time between statistics updates.

bEnableCPU
Enables CPU monitoring.
bEnableMemory
Enables memory monitoring.
bEnableDisk
Enables disk monitoring.
dMinTimeStampToGenerateStats
Minimum time between collections (in seconds). *** The dMinTimeStampToGenerateStats is a safety variable to prevent calculations that are too fast or outside the desired time window. To get correct CPU, Memory and Disk data, a time window between 500ms and 1000ms is recommended. Never set a time below 200ms. The default is 0.6 (600ms). Until 2026-10-11 it was 600.0, which in seconds meant 10 minutes.
function

Update

#
void Update( void );

Updates the monitored statistics. Collects and updates the CPU, memory and disk data according to the active settings, respecting the minimum interval between calculations. Must be called periodically.

*** Uses the initialization parameter dMinTimeStampToGenerateStats as the time window. If the time between the last statistics calculation and the current time (precision) is less than the value of that parameter the calculation is skipped and only runs once the time window/interval has at least been met.

*** This function must run in the main Backend/MainLoop that updates cycles/Ticks, for better data precision.

function

Shutdown

#
void Shutdown( void );

Shuts down the statistics manager. Disables the manager and stops the collection of statistical data.

function

GetCPUStatsCopy

#
const SStats GetCPUStatsCopy( const EStatsID StatsID );

Gets a copy of the CPU statistics. Returns a safe copy of the CPU statistical data for the requested scope (process or global).

StatsID
Identifier of the statistics type.
Copy of the CPU statistics.
function

GetMemoryStatsCopy

#
const SStats GetMemoryStatsCopy( const EStatsID StatsID );

Gets a copy of the memory statistics. Returns a safe copy of the memory usage statistical data for the requested scope.

StatsID
Identifier of the statistics type.
Copy of the memory statistics.
function

GetDiskReadStatsCopy

#
const SStats GetDiskReadStatsCopy( const EStatsID StatsID );

Gets a copy of the disk read statistics. Returns accumulated disk read data, with thread-safe access.

StatsID
Identifier of the statistics type.
Copy of the disk read statistics.
function

GetDiskWriteStatsCopy

#
const SStats GetDiskWriteStatsCopy( const EStatsID StatsID );

Gets a copy of the disk write statistics.

Returns accumulated disk write data, with thread-safe access.

StatsID
Identifier of the statistics type.
Copy of the disk write statistics.

thread.hpp

#include <ethereal/cpp/system/thread.hpp>
const

ETL_THREAD_WAIT_INFINITE

Ethereal::Thread#
static constexpr ETL_UINT32 ETL_THREAD_WAIT_INFINITE = 0xFFFFFFFFu;

Wait with no time limit.

Same value as the Win32 INFINITE constant, written here so that this header does not depend on <windows.h>.

const

ETL_THREAD_PRIORITY_NORMAL

Ethereal::Thread#
static constexpr ETL_INT32 ETL_THREAD_PRIORITY_NORMAL = 0;

Normal execution priority of a thread.

Same value as the Win32 THREAD_PRIORITY_NORMAL constant, written here so that this header does not depend on <windows.h>.

function

Start

Ethereal::Thread#
ETL_DWORD Start( unsigned ETL_STDCALL ThreadFunc(void*), ETL_PTR UserData, ETL_HANDLE & OutThreadHandle, uint32_t & OutThreadID );

Creates a routine (thread). The routine starts right after creation and runs the given callback function.

Windows and POSIX. On POSIX the 'handle' is an internal index ('ETL_HANDLE' is an 'int'), and 'OutThreadID' is the id the thread itself sees in GetCurrentThreadID.

ThreadFunc
Thread function (__stdcall format) to run.
UserData
Data pointer passed as the argument of the thread function.
OutThreadHandle
In-out parameter that receives the 'handle' of the created thread.
OutThreadID
In-out parameter that receives the ID of the created thread.
Error code of the operation. 0 on success, otherwise the system code (EINVAL on POSIX without a function): GetLastError() on Windows, errno or the pthread result on POSIX.
function

StartSuspended

Ethereal::Thread#
ETL_DWORD StartSuspended( unsigned ETL_STDCALL ThreadFunc(void*), ETL_PTR UserData, ETL_HANDLE & OutThreadHandle, uint32_t & OutThreadID );

Creates a suspended routine (thread) (manual mode). The routine is created but stays suspended until Resume() is called.

Windows and POSIX. On POSIX the thread starts and waits, before calling the function, until Resume releases it.

ThreadFunc
Thread function (__stdcall format) to run.
UserData
Data pointer passed as the argument of the thread function.
OutThreadHandle
In-out parameter that receives the 'handle' of the created thread.
OutThreadID
In-out parameter that receives the ID of the created thread.
Error code of the operation. 0 on success, otherwise the system code (EINVAL on POSIX without a function): GetLastError() on Windows, errno or the pthread result on POSIX.
function

SetPriority

Ethereal::Thread#
ETL_DWORD SetPriority( const ETL_HANDLE ThreadHandle, const ETL_INT32 PriorityCode = ETL_THREAD_PRIORITY_NORMAL );

Sets the execution priority of a routine (thread).

Windows (SetThreadPriority) and Linux, where the Win32 priorities become the thread 'nice' (IDLE 19, LOWEST 10, BELOW_NORMAL 5, NORMAL 0, ABOVE_NORMAL -5, HIGHEST -10, TIME_CRITICAL -20). Raising above normal needs privilege, and without it 'errno' is returned. Any other value: EINVAL. On macOS: ENOTSUP.

ThreadHandle
'Handle' of the thread whose priority will change.
PriorityCode
Priority code (e.g. THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_HIGHEST, etc).
Error code of the operation. 0 on success, 1 if the 'handle' is not valid, otherwise the system code: GetLastError() on Windows, errno or the pthread result on POSIX.
The default is written as ETL_THREAD_PRIORITY_NORMAL and not as the Win32 THREAD_PRIORITY_NORMAL constant: they have the same value, but the second only exists with <windows.h> included and kept this header from being read outside Windows.
function

Resume

Ethereal::Thread#
ETL_DWORD Resume( const ETL_HANDLE ThreadHandle );

Resumes a previously suspended routine (thread). If the thread is suspended, its execution continues.

Windows and POSIX. On POSIX it only releases a thread created by StartSuspended. On a thread that is already running it does nothing (and returns 0).

ThreadHandle
'Handle' of the thread to resume.
Error code of the operation. 0 on success, 1 if the 'handle' is not valid, otherwise the system code: GetLastError() on Windows, errno or the pthread result on POSIX.
function

Suspend

Ethereal::Thread#
ETL_DWORD Suspend( const ETL_HANDLE ThreadHandle );

Suspends the execution of a routine (thread). Use it with care, since suspending a routine (thread) can cause deadlocks or inconsistencies.

Windows only. On POSIX it returns ENOTSUP: there is no safe way to stop another thread midway (it could stop while holding a lock).

ThreadHandle
'Handle' of the thread to suspend.
Error code of the operation. 0 on success, 1 if the 'handle' is not valid, otherwise the system code: GetLastError() on Windows, errno or the pthread result on POSIX.
function

GetCurrentThreadID

Ethereal::Thread#
ETL_UINT64 GetCurrentThreadID( void ) noexcept;
function

WaitForThreadExit

Ethereal::Thread#
ETL_DWORD WaitForThreadExit( const ETL_HANDLE ThreadHandle, const ETL_DWORD TimeOutTimeMs = ETL_THREAD_WAIT_INFINITE );

Waits for the routine (thread) to finish, with an optional timeout.

Windows and POSIX. If the timeout expires with the thread alive, it returns WAIT_TIMEOUT (Windows) or ETIMEDOUT (POSIX), never 0.

ThreadHandle
Handle of the thread to wait for.
TimeOutTimeMs
Maximum wait time in milliseconds (INFINITE for an unlimited wait).
Error code of the operation. 0 on success, 1 if the 'handle' is not valid, otherwise the system code: GetLastError() on Windows, errno or the pthread result on POSIX.
function

ForceThreadTerminate

Ethereal::Thread#
ETL_DWORD ForceThreadTerminate( const ETL_HANDLE ThreadHandle, const ETL_DWORD ExitCode = 0 );

Forcibly terminates a running routine (thread). This function ends the thread with TerminateThread. Use it only in critical cases.

Windows only. On POSIX it returns ENOTSUP: 'pthread_cancel' is not a 'TerminateThread' (it only stops at cancellation points).

ThreadHandle
'Handle' of the thread to terminate.
ExitCode
Exit code assigned to the routine (thread).
Error code of the operation. 0 on success, 1 if the 'handle' is not valid, otherwise the system code: GetLastError() on Windows, errno or the pthread result on POSIX.
function

CloseThreadHandle

Ethereal::Thread#
void CloseThreadHandle( ETL_HANDLE & ThreadHandle );

Closes the handle of an open routine (thread). This is needed to avoid leaking system resources.

Windows and POSIX. It does not stop the thread, it only releases the 'handle'.

ThreadHandle
'Handle' of the thread, by reference. After closing, it is set to nullptr (ETL_INVALID_HANDLE on POSIX).
function

IsThreadFinished

Ethereal::Thread#
bool IsThreadFinished( const ETL_HANDLE ThreadHandle );

Checks whether a routine (thread) has already finished its execution.

Windows and POSIX.

ThreadHandle
'Handle' of the thread to check.
true if the thread has finished. false if it is still active.