...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Note | |
---|---|
This is an experimental feature. |
The experimental::promise
type and experimental::use_promise
completion token allow
eager execution and synchronisation of asynchronous operations. For example:
auto promise = async_read( stream, boost::asio::buffer(my_buffer), boost::asio::experimental::use_promise); ... do other stuff while the read is going on ... promise.async_wait( // completion the operation [](error_code ec, std::size_t bytes_read) { ... });
Promises can be safely disregarded if the result is no longer required. Different operations can be combined to either wait for all to complete or for one to complete (and cancel the rest). For example, to wait for one to complete:
auto timeout_promise = timer.async_wait( boost::asio::experimental::use_promise); auto read_promise = async_read( stream, boost::asio::buffer(my_buffer), boost::asio::experimental::use_promise); auto promise = boost::asio::experimental::make_parallel_group( timeout_promise.async_wait(boost::asio::deferred), read_promise.async_wait(boost::asio::deferred) ).async_wait( boost::asio::experimental::wait_for_one(), boost::asio::experimental::use_promise); promise.async_wait( [](std::array<std::size_t, 2> order, error_code timer_ec, error_code read_ec, std::size_t read_size) { if (order[0] == 0) { // timed out } else { // completed in time } });
or to wait for all to complete:
auto write_promise = async_write( stream, boost::asio::buffer(my_write_buffer), boost::asio::experimental::use_promise); auto read_promise = async_read( stream, boost::asio::buffer(my_buffer), boost::asio::experimental::use_promise); auto promise = boost::asio::experimental::make_parallel_group( timeout_promise.async_wait(boost::asio::deferred), read_promise.async_wait(boost::asio::deferred) ).async_wait( boost::asio::experimental::wait_for_all(), boost::asio::experimental::use_promise); promise.async_wait( [](std::array<std::size_t, 2> order, error_code timer_ec, error_code read_ec, std::size_t read_size) { // ... });