As we already defined above, An asynchronous
function, also called a promise, is a function
which returns a future and arranges for this future to be eventually
resolved. As we already saw, an asynchronous function is usually written
in terms of other asynchronous functions, for example we saw the
function slow()
which waits for the existing asynchronous
function sleep()
to complete, and then returns 3:
::future<int> slow() {
seastarusing namespace std::chrono_literals;
return seastar::sleep(100ms).then([] { return 3; });
}
The most basic building block for writing promises is the
promise object, an object of type
promise<T>
. A promise<T>
has a
method future<T> get_future()
to returns a future,
and a method set_value(T)
, to resolve this future. An
asynchronous function can create a promise object, return its future,
and the set_value
method to be eventually called - which
will finally resolve the future it returned.
In the following example we create a promise that manages the process
of printing 10 messages, once every second. We start by creating an
empty promise to work with. We then spin up a
seastart::thread
to perform the work we want. When the
work, printing those messages, is completed we call
promise::set_value
to mark the completion of the task.
Other than that we wait for the future which is generated by our
promise, just like any other future.
#include <seastar/core/future.hh>
#include <seastar/core/do_with.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/thread.hh>
#include <iostream>
::future<> f() {
seastarreturn seastar::do_with(seastar::promise<>(), [](auto& promise) {
(void)seastar::async([&promise]() {
using namespace std::chrono_literals;
for (int i = 0; i < 10; i++) {
std::cout << i << "..." << std::flush;
::sleep(1s).wait();
seastar}
std::cout << std::endl;
.set_value();
promise});
return promise.get_future();
});
}