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::CpuTaskExecutor Class Reference

Static utility class for executing CPU-intensive tasks asynchronously. More...

#include <CpuTaskExecutor.h>

Collaboration diagram for swt::CpuTaskExecutor:
Collaboration graph

Static Public Member Functions

template<typename Func >
static auto executeAsync (std::shared_ptr< SLLooper > resultLooper, Func &&func) -> Promise< decltype(func())>
 Execute CPU-bound task asynchronously without timeout.
 
template<typename Func >
static auto executeAsync (std::shared_ptr< SLLooper > resultLooper, Func &&func, std::chrono::milliseconds timeout) -> Promise< decltype(func())>
 Execute CPU-bound task asynchronously with timeout protection.
 

Detailed Description

Static utility class for executing CPU-intensive tasks asynchronously.

CpuTaskExecutor provides a high-level interface for executing CPU-bound tasks in separate threads while integrating seamlessly with the event loop pattern. Key features include:

  • Async execution: Uses std::async for guaranteed separate thread execution
  • Event loop integration: Results delivered via SLLooper for thread safety
  • Timeout support: Optional timeout protection against runaway computations
  • Exception safety: Comprehensive exception capture and propagation
  • Type safety: Template-based with automatic type deduction
  • Promise integration: Returns Promise objects for continuation chaining

Architecture:

  • Static methods: No instance state, pure utility class design
  • Template-based: Supports any callable with automatic return type deduction
  • Thread separation: CPU tasks execute in dedicated threads
  • Result posting: Thread-safe result delivery via event loop
  • Fire-and-forget: std::future used internally but Promise provides coordination

Use cases:

  • Mathematical computations: Fibonacci, prime numbers, matrix operations
  • Data processing: Large file processing, image manipulation
  • Cryptographic operations: Encryption, hashing, key generation
  • Network operations: HTTP requests, DNS lookups (with timeout)
  • File I/O: Large file operations that might block
// Simple CPU-bound task without timeout
auto promise1 = CpuTaskExecutor::executeAsync(looper, []() {
return fibonacci(45); // Long-running computation
});
// CPU-bound task with 5-second timeout protection
auto promise2 = CpuTaskExecutor::executeAsync(looper, []() {
return processLargeDataset(data);
}, 5000ms);
// Chain results with error handling
promise2.then(looper, [](auto result) {
std::cout << "Processing completed: " << result << std::endl;
}).catch_error(looper, [](std::exception_ptr ex) {
// Handle both timeout and function exceptions
});
static auto executeAsync(std::shared_ptr< SLLooper > resultLooper, Func &&func) -> Promise< decltype(func())>
Execute CPU-bound task asynchronously without timeout.
Note
All methods are static - no instance creation required
Functions execute in separate threads - ensure thread safety
Results are posted back to specified SLLooper thread
Warning
Avoid capturing event loop objects in task functions
See also
Promise, SLLooper, CpuTaskTimeoutException

Definition at line 128 of file CpuTaskExecutor.h.

Member Function Documentation

◆ executeAsync() [1/2]

template<typename Func >
static auto swt::CpuTaskExecutor::executeAsync ( std::shared_ptr< SLLooper resultLooper,
Func &&  func 
) -> Promise< decltype(func())>
static

Execute CPU-bound task asynchronously without timeout.

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

Executes CPU-intensive tasks in a separate thread without timeout limits. This is the preferred method for tasks with predictable execution times or when timeout protection is handled at a higher level.

Key characteristics:

  • No timeout limit: Task runs until completion or exception
  • Separate thread: Guaranteed execution in dedicated thread
  • Exception safety: All exceptions captured and propagated via Promise
  • Type deduction: Return type automatically deduced from function
  • Move semantics: Efficient parameter transfer to execution thread

Execution flow:

  1. Create Promise for result coordination
  2. Launch std::async task with std::launch::async policy
  3. Execute function in separate thread
  4. Capture result or exception
  5. Post result back to SLLooper thread
  6. Resolve Promise in event loop context
// Mathematical computation
auto fibPromise = CpuTaskExecutor::executeAsync(looper, []() {
return fibonacci(45);
});
// Data processing with parameters
std::vector<int> data = getData();
auto processPromise = CpuTaskExecutor::executeAsync(looper,
[data = std::move(data)]() {
return processData(data);
});
// Void-returning task
auto voidPromise = CpuTaskExecutor::executeAsync(looper, []() {
performSideEffect(); // No return value
});
Note
Implementation in CpuTaskExecutor.tpp
Function parameter passed by universal reference for efficiency
SLLooper parameter passed by value for safe capture
Supports both value-returning and void functions
See also
executeAsync(Func&&), Promise

◆ executeAsync() [2/2]

template<typename Func >
static auto swt::CpuTaskExecutor::executeAsync ( std::shared_ptr< SLLooper resultLooper,
Func &&  func,
std::chrono::milliseconds  timeout 
) -> Promise< decltype(func())>
static

Execute CPU-bound task asynchronously with timeout protection.

Template Parameters
FuncFunction type (auto-deduced)
Parameters
resultLooperSLLooper instance for result callback execution
funcCPU-intensive function to execute
timeoutMaximum execution time before timeout exception
Returns
Promise<ReturnType> Promise for result retrieval and chaining

Executes CPU-intensive tasks with timeout protection to prevent runaway computations from hanging the application. Uses a two-level async approach for precise timeout detection while maintaining the same Promise-based result delivery mechanism.

Key characteristics:

  • Timeout protection: CpuTaskTimeoutException after timeout period
  • Precise timing: Uses std::future::wait_for for accurate timeout detection
  • Two-level async: Outer timeout management, inner task execution
  • Exception discrimination: Separates timeout from function exceptions
  • Resource handling: Background cleanup of timed-out tasks

Timeout behavior:

  • Success case: Normal result delivery if completed within timeout
  • Timeout case: CpuTaskTimeoutException delivered via Promise
  • Exception case: Function exceptions delivered normally via Promise
  • Background cleanup: Timed-out tasks continue but results discarded
// Network operation with 10-second timeout
auto networkPromise = CpuTaskExecutor::executeAsync(looper, []() {
return downloadLargeFile(url);
}, 10000ms);
// Mathematical computation with 5-second timeout
auto mathPromise = CpuTaskExecutor::executeAsync(looper, []() {
return complexCalculation();
}, 5000ms);
// Handle timeout vs normal exceptions
mathPromise.catch_error(looper, [](std::exception_ptr ex) {
try {
std::rethrow_exception(ex);
} catch (const CpuTaskTimeoutException& timeout) {
// Specific timeout handling
std::cerr << "Operation timed out!" << std::endl;
} catch (const std::exception& other) {
// Other computation errors
std::cerr << "Computation error: " << other.what() << std::endl;
}
});
Note
Implementation in CpuTaskExecutor.tpp
Timeout resolution limited by std::future::wait_for precision
Timed-out tasks may continue running but results are discarded
Timeout duration included in CpuTaskTimeoutException message
Warning
Long-running tasks cannot be forcibly terminated after timeout
See also
CpuTaskTimeoutException, Promise

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