![]() |
Home | Libraries | People | FAQ | More |
A trampoline is an executor adapter that changes how function objects are executed when they are submitted from within a function object that is already running on the trampoline. Rather than being invoked recursively, or returned to the target executor's queue, these nested submissions are added to a queue on the current thread. They are then invoked, in order, once the current function object returns.
A trampoline is created by calling make_trampoline() with a target executor and the maximum
number of calls that may be queued:
auto ex = boost::asio::make_trampoline(my_io_context.get_executor(), 64);
A function object that is submitted to the trampoline from outside is passed
to the target executor, which invokes it within a newly installed trampoline.
While it runs, any function objects submitted through the same trampoline,
whether by post()
or dispatch(),
are added to the trampoline's queue. These queued function objects run
ahead of any other work that is pending on the target executor. Once the
trampoline has run the maximum number of calls, further submissions are
passed to the target executor as usual, so that other pending work is not
starved.
A trampoline is particularly useful when combined with immediate completion.
When an asynchronous operation completes immediately, and its completion
handler starts another operation that also completes immediately, delivering
the completion handlers via an inline_executor
results in unbounded recursion. By delivering them through a trampoline
instead, each completion handler is invoked after the previous one returns:
my_socket.async_read_some(my_buffer, boost::asio::bind_immediate_executor( my_trampoline, [](error_code e, size_t n) { // ... } ) );
The make_trampoline()
function also accepts an optional maximum inline depth. When this is non-zero,
a function object submitted by dispatch() may be invoked immediately, rather than
queued, provided the nesting of such calls does not exceed this depth.
Each trampoline created by make_trampoline() has its own identity, which is shared
by all copies of the trampoline executor. Function objects are added to
an installed trampoline's queue only when they are submitted through a
trampoline executor with the same identity.
trampoline, make_trampoline, bind_immediate_executor, Customising Immediate Completion.