Asynchronous Programming with Seastar

Nadav Har’El - nyh@ScyllaDB.com

Avi Kivity - avi@ScyllaDB.com

Back to table of contents. Previous: 22 Debugging a Seastar program. Next: 24 Memory allocation in Seastar.

23 Promise objects

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:

seastar::future<int> slow() {
    using 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>


seastar::future<> f() {
    return 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;
                    seastar::sleep(1s).wait();
                }
                std::cout << std::endl;

                promise.set_value();
        });

        return promise.get_future();
    });
}
Back to table of contents. Previous: 22 Debugging a Seastar program. Next: 24 Memory allocation in Seastar.