SW Task Event Loop Framework v1.0.0
High-performance C++ asynchronous event loop framework with timer management and promise-based programming
|
Central event loop coordinator providing asynchronous task execution and timer management. More...
#include <SLLooper.h>
Public Member Functions | |
SLLooper () | |
Constructor - initializes message queue and starts event loop. | |
~SLLooper () | |
Destructor - stops event loop and cleanup resources. | |
std::shared_ptr< EventQueue > | getEventQueue () |
Get access to the underlying event queue. | |
template<typename F , typename... Args> | |
auto | post_internal (F &&func, Args &&... args, const char *file, int line, const char *funcname) -> std::future< decltype(func(args...))> |
Internal post function with debug info for CPU-bound detection. | |
template<typename F , typename... Args> | |
auto | postDelayed_internal (int64_t delayMs, F &&func, Args &&... args, const char *file, int line, const char *funcname) -> std::future< decltype(func(args...))> |
Internal postDelayed function with debug info for CPU-bound detection. | |
template<typename F , typename... Args> | |
auto | post (F &&func, Args &&... args) -> std::future< decltype(func(args...))> |
Post function for immediate asynchronous execution. | |
template<typename F , typename... Args> | |
auto | postDelayed (int64_t delayMs, F &&func, Args &&... args) -> std::future< decltype(func(args...))> |
Post function for delayed asynchronous execution. | |
template<typename T > | |
swt::Promise< T > | createPromise () |
Create a new promise object for manual result setting. | |
template<typename Func > | |
auto | postWork (Func &&func) -> swt::Promise< decltype(func())> |
Execute CPU-intensive task asynchronously. | |
template<typename Func > | |
auto | postWork (Func &&func, std::chrono::milliseconds timeout) -> swt::Promise< decltype(func())> |
Execute CPU-intensive task with timeout. | |
template<typename Func > | |
auto | awaitWork (Func &&func) -> WorkAwaitable< decltype(func())> |
Execute function on background thread (co_await version) | |
DelayAwaitable | awaitDelay (int delayMs) |
Delay execution (co_await version) | |
template<typename Func > | |
auto | awaitPost (Func &&func) -> PostAwaitable< decltype(func())> |
Execute function on main thread (co_await version) | |
bool | loop () |
Run one iteration of the event loop. | |
void | exit () |
Request event loop to exit. | |
Timer | addTimer (std::function< void()> callback, uint64_t delay_ms) |
Add one-shot timer with millisecond precision. | |
template<typename Rep , typename Period > | |
Timer | addTimer (std::function< void()> callback, const std::chrono::duration< Rep, Period > &delay) |
Add one-shot timer with chrono duration. | |
Timer | addPeriodicTimer (std::function< void()> callback, uint64_t interval_ms) |
Add periodic timer with millisecond interval. | |
template<typename Rep , typename Period > | |
Timer | addPeriodicTimer (std::function< void()> callback, const std::chrono::duration< Rep, Period > &interval) |
Add periodic timer with chrono interval. | |
template<typename Function > | |
auto | postWithTimeout (Function &&func, uint64_t timeout_ms) -> std::enable_if_t< std::is_void_v< std::invoke_result_t< Function > >, Timer > |
Post function with timeout, returns Timer for cancellation. | |
TimerId | createTimerInternal (std::function< void()> callback, uint64_t delay_ms, bool periodic, std::atomic< bool > *cancelled) |
Internal timer creation method. | |
bool | cancelTimerInternal (TimerId id) |
Internal timer cancellation method. | |
bool | hasTimerInternal (TimerId id) |
Check if timer exists in internal management. | |
bool | restartTimerInternal (TimerId id, uint64_t delay_ms) |
Restart existing timer with new delay. | |
size_t | getActiveTimerCount () |
Get count of active timers. | |
void | initializeTimerManager () |
Initialize TimerManager lazily. | |
void | updateTimerCancelledPtr (TimerId id, std::atomic< bool > *newPtr) |
Update timer cancellation pointer for moved Timer objects. | |
Static Public Member Functions | |
static const char * | getTimerBackend () |
Get timer backend name. | |
Central event loop coordinator providing asynchronous task execution and timer management.
SLLooper is the core component of the SW Task Framework that coordinates:
The SLLooper follows the event loop pattern, continuously processing queued tasks and timer events in a single thread while providing thread-safe APIs for task submission from other threads.
Key design principles:
Definition at line 82 of file SLLooper.h.
swt::SLLooper::SLLooper | ( | ) |
Constructor - initializes message queue and starts event loop.
Creates EventQueue, starts the main event loop thread, and initializes internal state. TimerManager is created lazily on first timer request.
Definition at line 29 of file SLLooper.cpp.
References loop(), and SLLOOPER_INFO.
swt::SLLooper::~SLLooper | ( | ) |
Destructor - stops event loop and cleanup resources.
Performs orderly shutdown:
Definition at line 51 of file SLLooper.cpp.
References SLLOOPER_DEBUG, SLLOOPER_ERROR, SLLOOPER_ERROR_STREAM, and SLLOOPER_INFO.
Timer swt::SLLooper::addPeriodicTimer | ( | std::function< void()> | callback, |
const std::chrono::duration< Rep, Period > & | interval | ||
) |
Add periodic timer with chrono interval.
Rep | Duration representation type |
Period | Duration period type |
callback | Function to call on each timer expiration |
interval | Chrono interval between expirations |
Creates a periodic timer using chrono duration types for type-safe interval specifications.
Timer swt::SLLooper::addPeriodicTimer | ( | std::function< void()> | callback, |
uint64_t | interval_ms | ||
) |
Add periodic timer with millisecond interval.
callback | Function to call on each timer expiration |
interval_ms | Interval in milliseconds between expirations |
Creates a periodic timer that fires repeatedly at the specified interval. The callback executes in the event loop thread context on each expiration.
Definition at line 163 of file SLLooper.cpp.
References createTimerInternal(), initializeTimerManager(), swt::Timer::isActive(), SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.
Timer swt::SLLooper::addTimer | ( | std::function< void()> | callback, |
const std::chrono::duration< Rep, Period > & | delay | ||
) |
Add one-shot timer with chrono duration.
Rep | Duration representation type (e.g., int, long) |
Period | Duration period type (e.g., std::milli, std::micro) |
callback | Function to call when timer expires |
delay | Chrono duration (e.g., 500ms, 1s, 100us) |
Creates a one-shot timer using chrono duration types for type-safe timing specifications. Supports various duration types automatically.
Timer swt::SLLooper::addTimer | ( | std::function< void()> | callback, |
uint64_t | delay_ms | ||
) |
Add one-shot timer with millisecond precision.
callback | Function to call when timer expires |
delay_ms | Delay in milliseconds before timer expiration |
Creates a one-shot timer that fires once after the specified delay. The callback executes in the event loop thread context.
Definition at line 145 of file SLLooper.cpp.
References createTimerInternal(), initializeTimerManager(), swt::Timer::isActive(), SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.
|
inline |
Delay execution (co_await version)
Suspends the current coroutine for the specified duration and resumes execution after the delay. Uses SLLooper's timer system internally for precise timing.
delayMs | Delay in milliseconds |
Definition at line 406 of file SLLooper.h.
|
inline |
Execute function on main thread (co_await version)
Posts a function to execute on the main thread (SLLooper thread) and suspends the current coroutine until execution completes. Useful for updating UI or accessing thread-local resources from coroutines.
Func | Function type (auto-deduced from lambda/function) |
func | Function to execute on main thread |
Definition at line 443 of file SLLooper.h.
|
inline |
Execute function on background thread (co_await version)
Executes a function asynchronously on a background thread and resumes the awaiting coroutine on the main thread when complete. Provides seamless integration between coroutines and thread pool execution.
Func | Function type (auto-deduced from lambda/function) |
func | Function to execute on background thread |
Definition at line 375 of file SLLooper.h.
bool swt::SLLooper::cancelTimerInternal | ( | TimerId | id | ) |
Internal timer cancellation method.
id | Timer identifier to cancel |
Definition at line 207 of file SLLooper.cpp.
References SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.
swt::Promise< T > swt::SLLooper::createPromise | ( | ) |
Create a new promise object for manual result setting.
T | Value type for the promise |
Creates a new promise object that can be resolved manually from any thread. Useful for integrating with callback-based APIs or complex async workflows.
TimerId swt::SLLooper::createTimerInternal | ( | std::function< void()> | callback, |
uint64_t | delay_ms, | ||
bool | periodic, | ||
std::atomic< bool > * | cancelled | ||
) |
Internal timer creation method.
callback | Function to call when timer expires |
delay_ms | Delay in milliseconds |
periodic | true for repeating timer, false for one-shot |
cancelled | Pointer to atomic cancellation flag |
Low-level timer creation used internally by Timer objects. Creates TimerManager lazily if not already initialized.
Definition at line 190 of file SLLooper.cpp.
References initializeTimerManager(), SLLOOPER_DEBUG, SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.
Referenced by addPeriodicTimer(), and addTimer().
void swt::SLLooper::exit | ( | ) |
Request event loop to exit.
Signals the event loop to stop processing and exit gracefully. The loop will finish processing current messages before stopping.
Definition at line 75 of file SLLooper.cpp.
References SLLOOPER_DEBUG.
size_t swt::SLLooper::getActiveTimerCount | ( | ) |
Get count of active timers.
Useful for debugging and monitoring timer usage.
Definition at line 235 of file SLLooper.cpp.
std::shared_ptr< EventQueue > swt::SLLooper::getEventQueue | ( | ) |
Get access to the underlying event queue.
Provides direct access to the underlying EventQueue for advanced operations that require direct queue manipulation or integration with legacy message-based code. Most users should prefer the high-level post() methods instead.
Use cases for direct queue access:
Definition at line 82 of file SLLooper.cpp.
|
inlinestatic |
Get timer backend name.
Definition at line 472 of file SLLooper.h.
References swt::TimerManager::getBackendName().
bool swt::SLLooper::hasTimerInternal | ( | TimerId | id | ) |
Check if timer exists in internal management.
id | Timer identifier to check |
Definition at line 218 of file SLLooper.cpp.
void swt::SLLooper::initializeTimerManager | ( | ) |
Initialize TimerManager lazily.
Creates TimerManager instance on first timer request. Uses lazy initialization to avoid unnecessary resources.
Definition at line 38 of file SLLooper.cpp.
References SLLOOPER_DEBUG, and SLLOOPER_ERROR_STREAM.
Referenced by addPeriodicTimer(), addTimer(), and createTimerInternal().
bool swt::SLLooper::loop | ( | ) |
Run one iteration of the event loop.
Processes one batch of messages and timer events. Used internally by the event loop thread. Can be called manually for custom loop control.
Definition at line 86 of file SLLooper.cpp.
References swt::EventQueue::FUNCTION, swt::EventQueue::MESSAGE, SLLOOPER_DEBUG, SLLOOPER_DEBUG_ENABLED, SLLOOPER_DEBUG_STREAM, SLLOOPER_ERROR_STREAM, and SLLOOPER_INFO.
Referenced by SLLooper().
auto swt::SLLooper::post | ( | F && | func, |
Args &&... | args | ||
) | -> std::future< decltype(func(args...))> |
Post function for immediate asynchronous execution.
F | Function type (auto-deduced) |
Args | Variadic argument types (auto-deduced) |
func | Callable object to execute asynchronously |
args | Arguments to forward to the function |
Posts a function to the message queue for immediate asynchronous execution in the event loop thread. Uses perfect forwarding to preserve argument types and supports both callable objects and member functions.
auto swt::SLLooper::post_internal | ( | F && | func, |
Args &&... | args, | ||
const char * | file, | ||
int | line, | ||
const char * | funcname | ||
) | -> std::future< decltype(func(args...))> |
Internal post function with debug info for CPU-bound detection.
F | Function type (auto-deduced) |
Args | Variadic argument types (auto-deduced) |
func | Function to execute asynchronously |
args | Arguments to forward to the function |
file | Source file name (for debug output) |
line | Source line number (for debug output) |
funcname | Function name (for debug output) |
Internal implementation that adds CPU-bound task detection in debug builds. Warns if task execution exceeds CPU_BOUND_DETECT_THRESHOLD_MS (3000ms).
auto swt::SLLooper::postDelayed | ( | int64_t | delayMs, |
F && | func, | ||
Args &&... | args | ||
) | -> std::future< decltype(func(args...))> |
Post function for delayed asynchronous execution.
F | Function type (auto-deduced) |
Args | Variadic argument types (auto-deduced) |
delayMs | Delay in milliseconds before execution |
func | Callable object to execute asynchronously |
args | Arguments to forward to the function |
Posts a function to the message queue for delayed asynchronous execution. The function will be executed after the specified delay in the event loop thread.
auto swt::SLLooper::postDelayed_internal | ( | int64_t | delayMs, |
F && | func, | ||
Args &&... | args, | ||
const char * | file, | ||
int | line, | ||
const char * | funcname | ||
) | -> std::future< decltype(func(args...))> |
Internal postDelayed function with debug info for CPU-bound detection.
F | Function type (auto-deduced) |
Args | Variadic argument types (auto-deduced) |
delayMs | Delay in milliseconds before execution |
func | Function to execute asynchronously |
args | Arguments to forward to the function |
file | Source file name (for debug output) |
line | Source line number (for debug output) |
funcname | Function name (for debug output) |
Internal implementation for delayed execution with CPU-bound detection.
auto swt::SLLooper::postWithTimeout | ( | Function && | func, |
uint64_t | timeout_ms | ||
) | -> std::enable_if_t< std::is_void_v< std::invoke_result_t< Function > >, Timer > |
Post function with timeout, returns Timer for cancellation.
Function | Function type (auto-deduced) |
func | Function to execute after timeout |
timeout_ms | Timeout in milliseconds |
Convenience method that combines postDelayed with timer functionality. Only enabled for void-returning functions using SFINAE.
auto swt::SLLooper::postWork | ( | Func && | func | ) | -> swt::Promise< decltype(func())> |
Execute CPU-intensive task asynchronously.
Func | Function type (auto-deduced) |
func | CPU-intensive function to execute |
Executes CPU-intensive tasks using a dedicated thread pool to avoid blocking the main event loop. Returns a promise for result handling and continuation chaining.
auto swt::SLLooper::postWork | ( | Func && | func, |
std::chrono::milliseconds | timeout | ||
) | -> swt::Promise< decltype(func())> |
Execute CPU-intensive task with timeout.
Func | Function type (auto-deduced) |
func | CPU-intensive function to execute |
timeout | Maximum execution time |
Executes CPU-intensive tasks with a timeout limit. If the task doesn't complete within the timeout, the promise is rejected with a timeout exception.
bool swt::SLLooper::restartTimerInternal | ( | TimerId | id, |
uint64_t | delay_ms | ||
) |
Restart existing timer with new delay.
id | Timer identifier to restart |
delay_ms | New delay in milliseconds |
Definition at line 223 of file SLLooper.cpp.
References SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.
void swt::SLLooper::updateTimerCancelledPtr | ( | TimerId | id, |
std::atomic< bool > * | newPtr | ||
) |
Update timer cancellation pointer for moved Timer objects.
id | Timer identifier |
newPtr | New pointer to atomic cancellation flag |
Called when Timer objects are moved to update internal pointer references for proper cancellation handling.
Definition at line 181 of file SLLooper.cpp.
References SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.