Async Context
About Async Context
Concept
When an application starts, we create multiple threads, each with its own async context. Each context contains its own EventLoop, TimerPool, and TaskPool, all running in the same thread.
The context that executes the manapi::async::context::run method can create copies of itself.
Note
Example
Output:
TaskPool
TaskPool is unique to each EventLoop. You can add tasks to the EventLoop that will be executed in the next iteration.
Output:
Information
append_task(), you can use append_static_task(), which avoids dynamic memory allocation and stores only 64 bytes of information.TimerPool
TimerPool manages timeouts and intervals. Each timer has a priority level:
TIMER_IMPORTANT- The Async Context will continue running until no important timers remain.
This code will print 5000ms timeout reached and then terminate.
TIMER_DEFAULT- The Async Context does not wait for these timers to complete.
This code may not print the message unless the EventLoop remains active for more than 5 seconds.
Methods
TimerPool provides four main methods:
Timer Control
You can stop an active Timer at any time using the stop() method:
Output:
You can also use the again() method to reactivate or modify a timer:
Output:
Async Tasks
To execute manapi::future<> tasks, use the manapi::async::run method:
Note
manapi::async::run executes the callback in the current scope immediately when called.Warning
manapi::async::invoke() if you need to wait for lambda execution. Otherwise, data stored in the lambda may be destroyed prematurely.Stopping Mechanism
To stop the current context, use the asynchronous stop() method in the manapi::async::context class: