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

Thread-safe unified queue for messages and function tasks with timed execution. More...

#include <EventQueue.h>

Collaboration diagram for swt::EventQueue:
Collaboration graph

Classes

struct  QueueItem
 Unified queue item supporting both messages and function tasks. More...
 

Public Types

enum class  QueueItemType { MESSAGE , FUNCTION }
 Type discriminator for queue items. More...
 

Public Member Functions

 EventQueue ()
 Constructor - initializes empty queue.
 
 ~EventQueue ()
 Destructor - cleanup remaining items.
 
bool enqueueMessage (const std::shared_ptr< Message > &message, int64_t whenUs)
 Enqueue traditional message for timed execution.
 
std::shared_ptr< Messagepoll ()
 Poll for next ready message (legacy compatibility)
 
bool isQuit ()
 Check if quit message was received.
 
template<typename F , typename... Args>
auto enqueueFunction (F &&func, Args &&... args) -> std::future< decltype(func(args...))>
 Enqueue function for immediate asynchronous execution.
 
template<typename F , typename... Args>
auto enqueueFunctionDelayed (int64_t delayMs, F &&func, Args &&... args) -> std::future< decltype(func(args...))>
 Enqueue function for delayed asynchronous execution.
 
template<typename T >
Promise< T > enqueuePromise ()
 Create and enqueue promise for manual resolution.
 
std::optional< QueueItempollNext ()
 Poll for next ready queue item (unified interface)
 
void quit ()
 Request queue shutdown.
 
bool hasMessage (const std::shared_ptr< Handler > &h, int32_t what, void *obj)
 Check for specific message in queue.
 
int64_t uptimeMicros ()
 Get current system uptime in microseconds.
 

Detailed Description

Thread-safe unified queue for messages and function tasks with timed execution.

EventQueue provides a unified interface for queuing both traditional messages and modern function tasks with support for immediate and delayed execution. Key features:

  • Unified queue: Single deque handling both messages and function tasks
  • Timed execution: Support for delayed execution with microsecond precision
  • Thread safety: Full thread-safe operations with mutex protection
  • Type safety: Template-based function enqueuing with automatic type deduction
  • Future support: std::future integration for result retrieval
  • Promise integration: Built-in promise creation and management
  • Efficient ordering: Binary search insertion for delayed tasks

The queue maintains chronological order for timed items while supporting immediate execution for urgent tasks. Uses type erasure to store different function signatures uniformly while preserving type safety at the API level.

Architecture:

  • QueueItem: Variant-like structure supporting messages and function tasks
  • Binary heap ordering: Maintains execution order based on timestamps
  • Condition variable: Efficient thread synchronization for polling
  • Move semantics: Optimal performance for large function objects
EventQueue queue;
// Enqueue immediate function
auto future1 = queue.enqueueFunction([](int x) { return x * 2; }, 21);
// Enqueue delayed function
auto future2 = queue.enqueueFunctionDelayed(1000, []() {
return "Hello after 1 second!";
});
// Traditional message support
auto msg = std::make_shared<Message>();
queue.enqueueMessage(msg, uptimeMicros() + 500000); // 500ms delay
// Poll for next item
while (auto item = queue.pollNext()) {
if (item->type == QueueItemType::FUNCTION) {
item->task(); // Execute function
} else {
// Handle message
}
}
Thread-safe unified queue for messages and function tasks with timed execution.
Definition EventQueue.h:86
std::optional< QueueItem > pollNext()
Poll for next ready queue item (unified interface)
int64_t uptimeMicros()
Get current system uptime in microseconds.
@ FUNCTION
Function task with std::packaged_task.
auto enqueueFunctionDelayed(int64_t delayMs, F &&func, Args &&... args) -> std::future< decltype(func(args...))>
Enqueue function for delayed asynchronous execution.
bool enqueueMessage(const std::shared_ptr< Message > &message, int64_t whenUs)
Enqueue traditional message for timed execution.
auto enqueueFunction(F &&func, Args &&... args) -> std::future< decltype(func(args...))>
Enqueue function for immediate asynchronous execution.
Note
Thread-safe for concurrent producers and single consumer
Warning
Consumer polling should be from single thread for message ordering
See also
Message, Handler, Promise

Definition at line 85 of file EventQueue.h.

Member Enumeration Documentation

◆ QueueItemType

enum class swt::EventQueue::QueueItemType
strong

Type discriminator for queue items.

Identifies whether a queue item contains a traditional message or a modern function task for proper handling during polling.

Enumerator
MESSAGE 

Traditional message with handler.

FUNCTION 

Function task with std::packaged_task.

Definition at line 95 of file EventQueue.h.

Constructor & Destructor Documentation

◆ EventQueue()

swt::EventQueue::EventQueue ( )

Constructor - initializes empty queue.

Creates an empty event queue with initialized mutex and condition variable for thread-safe operations.

Definition at line 13 of file EventQueue.cpp.

◆ ~EventQueue()

swt::EventQueue::~EventQueue ( )

Destructor - cleanup remaining items.

Cleans up any remaining messages and function tasks in the queue. Note that pending futures may become invalid after destruction.

Definition at line 19 of file EventQueue.cpp.

Member Function Documentation

◆ enqueueFunction()

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

Enqueue 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

Enqueues a function for immediate execution at the front of the queue. Uses perfect forwarding to preserve argument types and std::packaged_task for type-safe result retrieval through futures.

Note
Implementation in EventQueue.tpp
Thread-safe operation with immediate notification
See also
Promise

◆ enqueueFunctionDelayed()

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

Enqueue 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

Enqueues a function for delayed execution, maintaining chronological order with other timed items. Uses binary search insertion for efficient ordering without full queue sorting.

Note
Implementation in EventQueue.tpp
Thread-safe operation with conditional notification
See also
Promise

◆ enqueueMessage()

bool swt::EventQueue::enqueueMessage ( const std::shared_ptr< Message > &  message,
int64_t  whenUs 
)

Enqueue traditional message for timed execution.

Parameters
messageShared pointer to message object
whenUsAbsolute execution time in microseconds
Returns
true if message was successfully enqueued

Enqueues a traditional message for execution at the specified time. Messages are inserted in chronological order using binary search for efficient ordering without full sorting.

auto msg = std::make_shared<Message>();
msg->what = MSG_TIMEOUT;
queue.enqueueMessage(msg, uptimeMicros() + 1000000); // 1 second delay
Note
Thread-safe operation
Uses binary search for O(log n) insertion
See also
Message

Definition at line 31 of file EventQueue.cpp.

◆ enqueuePromise()

template<typename T >
template swt::Promise< void > swt::EventQueue::enqueuePromise< void > ( )

Create and enqueue promise for manual resolution.

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

Creates a new promise that can be resolved manually from any thread. The promise callbacks will execute in the event loop thread when the promise is resolved or rejected.

auto promise = queue.enqueuePromise<int>();
// Set up continuation in event loop thread
promise.then(looper, [](int result) {
std::cout << "Promise resolved: " << result << std::endl;
});
// Resolve from any thread
std::thread([promise]() mutable {
std::this_thread::sleep_for(1s);
promise.set_value(42);
}).detach();
Note
Promise callbacks execute in event loop thread
Thread-safe promise resolution from any thread
See also
Promise

◆ hasMessage()

bool swt::EventQueue::hasMessage ( const std::shared_ptr< Handler > &  h,
int32_t  what,
void *  obj 
)

Check for specific message in queue.

Parameters
hHandler to match
whatMessage type to match
objObject pointer to match
Returns
true if matching message found

Legacy method for checking if a specific message type is queued. Used for message deduplication and state checking.

See also
Handler

Definition at line 152 of file EventQueue.cpp.

References MESSAGE.

◆ isQuit()

bool swt::EventQueue::isQuit ( )

Check if quit message was received.

Returns
true if quit message is pending

Legacy method for checking quit state in message-based loops.

Definition at line 52 of file EventQueue.cpp.

◆ poll()

std::shared_ptr< Message > swt::EventQueue::poll ( )

Poll for next ready message (legacy compatibility)

Returns
Shared pointer to next ready message, or nullptr if none

Legacy method that polls only for messages, ignoring function tasks. Provided for backward compatibility with existing message-based code.

Note
Prefer pollNext() for unified polling
Only returns MESSAGE type items
See also
Message

Definition at line 142 of file EventQueue.cpp.

References MESSAGE, and pollNext().

Here is the call graph for this function:

◆ pollNext()

std::optional< EventQueue::QueueItem > swt::EventQueue::pollNext ( )

Poll for next ready queue item (unified interface)

Returns
std::optional<QueueItem> Next ready item, or nullopt if none

Unified polling method that returns the next ready item regardless of type (message or function). Checks timing and only returns items whose execution time has arrived. Blocks until an item is ready or the queue is quit.

while (auto item = queue.pollNext()) {
switch (item->type) {
handleMessage(item->message);
break;
item->task(); // Execute function
break;
}
}
@ MESSAGE
Traditional message with handler.
Note
Blocks until item is ready or quit is called
Thread-safe for single consumer
Preferred method for modern event loop implementations
See also
Message

Definition at line 56 of file EventQueue.cpp.

References uptimeMicros().

Referenced by poll().

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

◆ quit()

void swt::EventQueue::quit ( )

Request queue shutdown.

Signals the queue to stop processing and causes polling methods to return null/empty to exit event loop gracefully.

Definition at line 170 of file EventQueue.cpp.

◆ uptimeMicros()

int64_t swt::EventQueue::uptimeMicros ( )

Get current system uptime in microseconds.

Returns
int64_t Current uptime in microseconds

Utility method providing high-precision timing for queue scheduling. Uses steady_clock to avoid issues with system time adjustments.

Note
Uses std::chrono::steady_clock for monotonic timing
Microsecond precision for accurate scheduling

Definition at line 179 of file EventQueue.cpp.

Referenced by pollNext().

Here is the caller graph for this function:

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