What's Changed
future<>::on_completion()
New on_completion() interface on future<>. This allows notification when a future is complete. This is a low-level call used in the improved coroutine support. The completion function has a signature void() noexcept. It consumes a continuation slot, but does not consume the future, so if used on a move-only future, it consumes the only continuation slot, and it is UB to attach a continuation (such as with then() or recover()) after. Example:
auto f = stlab::async(default_executor, [] { return "world!\n"; }); f.on_completion([]() noexcept { std::cerr << "Hello "; }); std::cerr << stlab::await(std::move(f));
This will print:
Hello world!
Coroutine cancellation for future<>.
Cancellation of coroutines is now supported. When a coroutine returning a future awaits a future, the coroutine may be canceled while suspended. Example:
auto coroutine(future<int> f) -> future<int> { std::cout<< "start\n"; int x = co_await std::move(f); std::cout<< "finish\n"; co_return x + 5; } int main() { auto [p, f] = package<int(int)>(immediate_executor, std::identity{}); (void)coroutine(std::move(f)); // drop the result to cancel p(42); // fulfill the promise }
This will print:
start
resume_on()
The resume_on() function takes a future and an executor and returns an Awaitable. This allows you to specify the execution context for resuming a coroutine. Example:
auto coroutine(future<int> f) -> future<int> { int x = co_await resume_on(main_executor, f); x += 42; // do this on the main thread co_return x; }
The resume_on() function can be passed just an executor to immediately continue execution on the supplied executor. For both forms of resume_on(), if called in a coroutine that returns a future and all copies of the future are released, the operation may be canceled while suspended. Example:
(void)coroutine(async(immediate_executor, []{ return 42; })); // drop future to cancel // might never resume from the co_await and not execute `x+= 42;`
doctest
Moved from BoostTest to doctest as part of the migration towards using stlab/cpp-library for this project. This improves the build times for the tests and the developer experience in VSCode/Cursor using the C++ TestMate extension.
- Improvements to coroutine support for
future<>by @sean-parent in #590
Full Changelog: v2.2.0...v2.3.0