SW Task Event Loop Framework v1.0.0
High-performance C++ asynchronous event loop framework with timer management and promise-based programming
Loading...
Searching...
No Matches
swt::SLLooper Class Reference

Central event loop coordinator providing asynchronous task execution and timer management. More...

#include <SLLooper.h>

Inheritance diagram for swt::SLLooper:
Inheritance graph
Collaboration diagram for swt::SLLooper:
Collaboration graph

Public Member Functions

 SLLooper ()
 Constructor - initializes message queue and starts event loop.
 
 ~SLLooper ()
 Destructor - stops event loop and cleanup resources.
 
std::shared_ptr< EventQueuegetEventQueue ()
 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.
 

Detailed Description

Central event loop coordinator providing asynchronous task execution and timer management.

SLLooper is the core component of the SW Task Framework that coordinates:

  • Message queue processing: Unified queue for messages and function tasks
  • Timer management: High-performance Linux timerfd-based timers
  • Asynchronous execution: Function posting with futures and promises
  • CPU-bound task handling: Specialized executor for long-running tasks
  • Thread safety: Safe cross-thread communication via message passing
  • Coroutine support: Modern C++20 co_await integration

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:

  • Non-blocking operations: All APIs return immediately with futures/promises
  • RAII resource management: Automatic cleanup of timers and tasks
  • Boost-style timer API: Familiar interface for timer operations
  • Template-based: Type-safe function posting with perfect forwarding
  • Coroutine integration: Native co_await support for modern async patterns
// Create event loop
auto looper = std::make_shared<SLLooper>();
// Traditional async API
auto future = looper->post([](int x) { return x * 2; }, 21);
int result = future.get(); // result = 42
// Coroutine API (C++20)
Task<int> asyncWork() {
int result = co_await looper->awaitWork([]() { return 42; });
co_await looper->awaitDelay(1000); // Wait 1 second
co_return result;
}
// CPU-bound task with promise
auto promise = looper->postWork([]() {
return heavyComputation();
});
promise.then([](auto result) {
std::cout << "Work completed: " << result << std::endl;
});
RAII wrapper for coroutines with proper continuation chaining.
Definition Task.h:303
Note
Thread-safe for task submission, but not for direct member access
Warning
Must be created as shared_ptr due to enable_shared_from_this usage
See also
EventQueue, TimerManager, Timer, Promise, Task

Definition at line 82 of file SLLooper.h.

Constructor & Destructor Documentation

◆ SLLooper()

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.

Note
Must be created as shared_ptr: auto looper = std::make_shared<SLLooper>()

Definition at line 29 of file SLLooper.cpp.

References loop(), and SLLOOPER_INFO.

Here is the call graph for this function:

◆ ~SLLooper()

swt::SLLooper::~SLLooper ( )

Destructor - stops event loop and cleanup resources.

Performs orderly shutdown:

  1. Stop the main event loop thread
  2. Cancel all active timers via TimerManager
  3. Cleanup message queue and other resources

Definition at line 51 of file SLLooper.cpp.

References SLLOOPER_DEBUG, SLLOOPER_ERROR, SLLOOPER_ERROR_STREAM, and SLLOOPER_INFO.

Member Function Documentation

◆ addPeriodicTimer() [1/2]

template<typename Rep , typename Period >
Timer swt::SLLooper::addPeriodicTimer ( std::function< void()>  callback,
const std::chrono::duration< Rep, Period > &  interval 
)

Add periodic timer with chrono interval.

Template Parameters
RepDuration representation type
PeriodDuration period type
Parameters
callbackFunction to call on each timer expiration
intervalChrono interval between expirations
Returns
Timer RAII object for timer management

Creates a periodic timer using chrono duration types for type-safe interval specifications.

using namespace std::chrono_literals;
auto heartbeat = looper->addPeriodicTimer([]() {
sendHeartbeat();
}, 30s); // Every 30 seconds
Note
Implementation in SLLooper.tpp
See also
Timer

◆ addPeriodicTimer() [2/2]

Timer swt::SLLooper::addPeriodicTimer ( std::function< void()>  callback,
uint64_t  interval_ms 
)

Add periodic timer with millisecond interval.

Parameters
callbackFunction to call on each timer expiration
interval_msInterval in milliseconds between expirations
Returns
Timer RAII object for timer management

Creates a periodic timer that fires repeatedly at the specified interval. The callback executes in the event loop thread context on each expiration.

Timer periodicTimer = looper->addPeriodicTimer([]() {
std::cout << "Periodic tick!" << std::endl;
}, 1000); // Every second
// Stop after some time
looper->postDelayed(10000, [&periodicTimer]() {
periodicTimer.cancel();
});
RAII timer wrapper with boost-style API and move semantics.
Definition Timer.h:68
void cancel()
Cancel the timer.
Definition Timer.cpp:59
Note
Timer continues until cancelled or Timer object is destroyed
See also
Timer

Definition at line 163 of file SLLooper.cpp.

References createTimerInternal(), initializeTimerManager(), swt::Timer::isActive(), SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.

Here is the call graph for this function:

◆ addTimer() [1/2]

template<typename Rep , typename Period >
Timer swt::SLLooper::addTimer ( std::function< void()>  callback,
const std::chrono::duration< Rep, Period > &  delay 
)

Add one-shot timer with chrono duration.

Template Parameters
RepDuration representation type (e.g., int, long)
PeriodDuration period type (e.g., std::milli, std::micro)
Parameters
callbackFunction to call when timer expires
delayChrono duration (e.g., 500ms, 1s, 100us)
Returns
Timer RAII object for timer management

Creates a one-shot timer using chrono duration types for type-safe timing specifications. Supports various duration types automatically.

using namespace std::chrono_literals;
// Various duration types
auto timer1 = looper->addTimer(callback, 500ms);
auto timer2 = looper->addTimer(callback, 1s);
auto timer3 = looper->addTimer(callback, 2min);
Note
Implementation in SLLooper.tpp
Duration is converted to milliseconds internally
See also
Timer

◆ addTimer() [2/2]

Timer swt::SLLooper::addTimer ( std::function< void()>  callback,
uint64_t  delay_ms 
)

Add one-shot timer with millisecond precision.

Parameters
callbackFunction to call when timer expires
delay_msDelay in milliseconds before timer expiration
Returns
Timer RAII object for timer management

Creates a one-shot timer that fires once after the specified delay. The callback executes in the event loop thread context.

Timer timer = looper->addTimer([]() {
std::cout << "Timer fired after 1 second!" << std::endl;
}, 1000);
// Timer can be cancelled
if (shouldCancel) {
timer.cancel();
}
Note
Timer automatically cancels when Timer object is destroyed
See also
Timer, TimerManager

Definition at line 145 of file SLLooper.cpp.

References createTimerInternal(), initializeTimerManager(), swt::Timer::isActive(), SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.

Here is the call graph for this function:

◆ awaitDelay()

DelayAwaitable swt::SLLooper::awaitDelay ( int  delayMs)
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.

Parameters
delayMsDelay in milliseconds
Returns
DelayAwaitable Awaitable object for co_await
Task<void> example() {
std::cout << "Starting delay..." << std::endl;
co_await looper->awaitDelay(1000); // Wait 1 second
std::cout << "Delay completed!" << std::endl;
}
Note
Non-blocking: doesn't block the event loop during delay
Precise timing: uses Linux timerfd for accurate delays
Cancellation: delay is cancelled if Task is destroyed
Thread-safe: can be called from any thread
See also
DelayAwaitable, TimerManager

Definition at line 406 of file SLLooper.h.

◆ awaitPost()

template<typename Func >
auto swt::SLLooper::awaitPost ( Func &&  func) -> PostAwaitable<decltype(func())>
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.

Template Parameters
FuncFunction type (auto-deduced from lambda/function)
Parameters
funcFunction to execute on main thread
Returns
PostAwaitable<ReturnType> Awaitable object for co_await
Task<void> example() {
// Background work
auto data = co_await looper->awaitWork([]() {
return fetchDataFromNetwork();
});
// Update UI on main thread
co_await looper->awaitPost([data]() {
updateUI(data);
});
}
Note
Function executes on main thread (SLLooper thread)
Immediate execution: no additional threading overhead
Exception safety: exceptions are propagated to co_await site
Thread-safe: can be called from any thread
See also
PostAwaitable, Task

Definition at line 443 of file SLLooper.h.

◆ awaitWork()

template<typename Func >
auto swt::SLLooper::awaitWork ( Func &&  func) -> WorkAwaitable<decltype(func())>
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.

Template Parameters
FuncFunction type (auto-deduced from lambda/function)
Parameters
funcFunction to execute on background thread
Returns
WorkAwaitable<ReturnType> Awaitable object for co_await
Task<int> example() {
// Heavy computation on background thread
int result = co_await looper->awaitWork([]() {
return fibonacci(40);
});
// Execution resumes on main thread
std::cout << "Result: " << result << std::endl;
co_return result;
}
Note
Function executes on background thread
Coroutine resumes on main thread (SLLooper thread)
Exception safety: exceptions are propagated to co_await site
Thread-safe: can be called from any thread
See also
WorkAwaitable, Task

Definition at line 375 of file SLLooper.h.

◆ cancelTimerInternal()

bool swt::SLLooper::cancelTimerInternal ( TimerId  id)

Internal timer cancellation method.

Parameters
idTimer identifier to cancel
Returns
true if timer was found and cancelled
Note
For internal use by Timer class
See also
TimerManager

Definition at line 207 of file SLLooper.cpp.

References SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.

◆ createPromise()

template<typename T >
swt::Promise< T > swt::SLLooper::createPromise ( )

Create a new promise object for manual result setting.

Template Parameters
TValue type for the promise
Returns
swt::Promise<T> New promise object

Creates a new promise object that can be resolved manually from any thread. Useful for integrating with callback-based APIs or complex async workflows.

auto promise = looper->createPromise<int>();
// Set up continuation
promise.then([](int result) {
std::cout << "Promise resolved with: " << result << std::endl;
});
// Resolve from another thread
std::thread([promise]() mutable {
std::this_thread::sleep_for(1s);
promise.set_value(42);
}).detach();
Note
Implementation in SLLooper.tpp
See also
Promise, Future

◆ createTimerInternal()

TimerId swt::SLLooper::createTimerInternal ( std::function< void()>  callback,
uint64_t  delay_ms,
bool  periodic,
std::atomic< bool > *  cancelled 
)

Internal timer creation method.

Parameters
callbackFunction to call when timer expires
delay_msDelay in milliseconds
periodictrue for repeating timer, false for one-shot
cancelledPointer to atomic cancellation flag
Returns
TimerId Unique timer identifier

Low-level timer creation used internally by Timer objects. Creates TimerManager lazily if not already initialized.

Note
For internal use by Timer class
See also
TimerManager

Definition at line 190 of file SLLooper.cpp.

References initializeTimerManager(), SLLOOPER_DEBUG, SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.

Referenced by addPeriodicTimer(), and addTimer().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ exit()

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.

◆ getActiveTimerCount()

size_t swt::SLLooper::getActiveTimerCount ( )

Get count of active timers.

Returns
Number of currently active timers

Useful for debugging and monitoring timer usage.

See also
TimerManager

Definition at line 235 of file SLLooper.cpp.

◆ getEventQueue()

std::shared_ptr< EventQueue > swt::SLLooper::getEventQueue ( )

Get access to the underlying event queue.

Returns
std::shared_ptr<EventQueue> Shared pointer to the 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:

  • Legacy integration: Working with existing message-based code
  • Advanced operations: Custom message handling or queue manipulation
  • Performance optimization: Bypassing SLLooper abstractions when needed
  • Testing: Direct queue state inspection for unit tests
auto looper = std::make_shared<SLLooper>();
auto queue = looper->getEventQueue();
// Direct message enqueueing (legacy style)
auto message = std::make_shared<Message>();
queue->enqueueMessage(message, uptimeMicros() + 1000000);
// Direct function enqueueing (bypassing SLLooper)
auto future = queue->enqueueFunction([]() { return 42; });
Note
Use with caution - direct queue access bypasses SLLooper's abstractions
Prefer SLLooper's post() methods for most use cases
Thread-safe operation (EventQueue is thread-safe)
Warning
Direct queue manipulation may interfere with SLLooper's internal operations
See also
EventQueue, post(), postDelayed()

Definition at line 82 of file SLLooper.cpp.

◆ getTimerBackend()

static const char * swt::SLLooper::getTimerBackend ( )
inlinestatic

Get timer backend name.

Returns
Backend name string

Definition at line 472 of file SLLooper.h.

References swt::TimerManager::getBackendName().

Here is the call graph for this function:

◆ hasTimerInternal()

bool swt::SLLooper::hasTimerInternal ( TimerId  id)

Check if timer exists in internal management.

Parameters
idTimer identifier to check
Returns
true if timer exists and is active
Note
For internal use by Timer class
See also
TimerManager

Definition at line 218 of file SLLooper.cpp.

◆ initializeTimerManager()

void swt::SLLooper::initializeTimerManager ( )

Initialize TimerManager lazily.

Creates TimerManager instance on first timer request. Uses lazy initialization to avoid unnecessary resources.

Note
Called automatically when first timer is created
See also
TimerManager

Definition at line 38 of file SLLooper.cpp.

References SLLOOPER_DEBUG, and SLLOOPER_ERROR_STREAM.

Referenced by addPeriodicTimer(), addTimer(), and createTimerInternal().

Here is the caller graph for this function:

◆ loop()

bool swt::SLLooper::loop ( )

Run one iteration of the event loop.

Returns
true if loop should continue, false to exit

Processes one batch of messages and timer events. Used internally by the event loop thread. Can be called manually for custom loop control.

Note
Not typically called by user code

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().

Here is the caller graph for this function:

◆ post()

template<typename F , typename... Args>
auto swt::SLLooper::post ( F &&  func,
Args &&...  args 
) -> std::future< decltype(func(args...))>

Post function for immediate asynchronous execution.

Template Parameters
FFunction type (auto-deduced)
ArgsVariadic argument types (auto-deduced)
Parameters
funcCallable object to execute asynchronously
argsArguments to forward to the function
Returns
std::future<ReturnType> Future containing the function result

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.

// Lambda with capture
auto future1 = looper->post([x = 42](int y) { return x + y; }, 8);
// Free function
auto future2 = looper->post(std::sin, 3.14159);
// Member function
MyClass obj;
auto future3 = looper->post(&MyClass::method, &obj, arg1, arg2);
Note
Thread-safe operation
Function executes in event loop thread context
Implementation in SLLooper.tpp
See also
postDelayed(), postWithTimeout()

◆ post_internal()

template<typename F , typename... Args>
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.

Template Parameters
FFunction type (auto-deduced)
ArgsVariadic argument types (auto-deduced)
Parameters
funcFunction to execute asynchronously
argsArguments to forward to the function
fileSource file name (for debug output)
lineSource line number (for debug output)
funcnameFunction name (for debug output)
Returns
std::future<ReturnType> Future containing the function result

Internal implementation that adds CPU-bound task detection in debug builds. Warns if task execution exceeds CPU_BOUND_DETECT_THRESHOLD_MS (3000ms).

Note
For internal use - prefer post() for normal usage
Implementation in SLLooper.tpp

◆ postDelayed()

template<typename F , typename... Args>
auto swt::SLLooper::postDelayed ( int64_t  delayMs,
F &&  func,
Args &&...  args 
) -> std::future< decltype(func(args...))>

Post function for delayed asynchronous execution.

Template Parameters
FFunction type (auto-deduced)
ArgsVariadic argument types (auto-deduced)
Parameters
delayMsDelay in milliseconds before execution
funcCallable object to execute asynchronously
argsArguments to forward to the function
Returns
std::future<ReturnType> Future containing the function result

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.

// Execute after 1 second
auto future = looper->postDelayed(1000, []() {
return "Hello after delay!";
});
// Get result (blocks until execution completes)
std::string result = future.get();
Note
Thread-safe operation
Delay is measured from when the function is posted
Implementation in SLLooper.tpp
See also
post()

◆ postDelayed_internal()

template<typename F , typename... Args>
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.

Template Parameters
FFunction type (auto-deduced)
ArgsVariadic argument types (auto-deduced)
Parameters
delayMsDelay in milliseconds before execution
funcFunction to execute asynchronously
argsArguments to forward to the function
fileSource file name (for debug output)
lineSource line number (for debug output)
funcnameFunction name (for debug output)
Returns
std::future<ReturnType> Future containing the function result

Internal implementation for delayed execution with CPU-bound detection.

Note
For internal use - prefer postDelayed() for normal usage
Implementation in SLLooper.tpp

◆ postWithTimeout()

template<typename Function >
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.

Template Parameters
FunctionFunction type (auto-deduced)
Parameters
funcFunction to execute after timeout
timeout_msTimeout in milliseconds
Returns
Timer Timer object for cancellation

Convenience method that combines postDelayed with timer functionality. Only enabled for void-returning functions using SFINAE.

Timer timeoutTimer = looper->postWithTimeout([]() {
std::cout << "Timeout occurred!" << std::endl;
}, 5000);
// Can cancel before timeout
if (conditionMet) {
timeoutTimer.cancel();
}
Note
Only works with void-returning functions
Implementation in SLLooper.tpp
See also
Timer

◆ postWork() [1/2]

template<typename Func >
auto swt::SLLooper::postWork ( Func &&  func) -> swt::Promise< decltype(func())>

Execute CPU-intensive task asynchronously.

Template Parameters
FuncFunction type (auto-deduced)
Parameters
funcCPU-intensive function to execute
Returns
swt::Promise<ReturnType> Promise for result retrieval and chaining

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 promise = looper->postWork([]() {
// CPU-intensive computation
return fibonacci(45);
});
promise.then([](long result) {
std::cout << "Computation result: " << result << std::endl;
}).catch_error([](std::exception_ptr ex) {
std::cerr << "Computation failed!" << std::endl;
});
Note
Uses separate thread pool, doesn't block event loop
Implementation in SLLooper.tpp
See also
CpuTaskExecutor, Promise

◆ postWork() [2/2]

template<typename Func >
auto swt::SLLooper::postWork ( Func &&  func,
std::chrono::milliseconds  timeout 
) -> swt::Promise< decltype(func())>

Execute CPU-intensive task with timeout.

Template Parameters
FuncFunction type (auto-deduced)
Parameters
funcCPU-intensive function to execute
timeoutMaximum execution time
Returns
swt::Promise<ReturnType> Promise for result retrieval

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.

auto promise = looper->postWork([]() {
return longRunningComputation();
}, 5000ms);
promise.then([](auto result) {
std::cout << "Completed in time: " << result << std::endl;
}).catch_error([](std::exception_ptr ex) {
// Handle timeout or other errors
});
Note
Implementation in SLLooper.tpp
See also
CpuTaskExecutor, Promise

◆ restartTimerInternal()

bool swt::SLLooper::restartTimerInternal ( TimerId  id,
uint64_t  delay_ms 
)

Restart existing timer with new delay.

Parameters
idTimer identifier to restart
delay_msNew delay in milliseconds
Returns
true if timer was found and restarted
Note
For internal use by Timer class
See also
TimerManager

Definition at line 223 of file SLLooper.cpp.

References SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.

◆ updateTimerCancelledPtr()

void swt::SLLooper::updateTimerCancelledPtr ( TimerId  id,
std::atomic< bool > *  newPtr 
)

Update timer cancellation pointer for moved Timer objects.

Parameters
idTimer identifier
newPtrNew pointer to atomic cancellation flag

Called when Timer objects are moved to update internal pointer references for proper cancellation handling.

Note
For internal use by Timer move operations
See also
Timer

Definition at line 181 of file SLLooper.cpp.

References SLLOOPER_DEBUG_STREAM, and SLLOOPER_ERROR.


The documentation for this class was generated from the following files: