All Recipes
Home/Coroutines/Async/Await Pattern
advanced

Async/Await Pattern

Implement async operations using coroutines

Example Code

cpp
#include <coroutine>
#include <iostream>
#include <thread>
#include <chrono>
#include <functional>
// Simple async task type
struct Task {
struct promise_type {
int result;
std::function<void()> continuation;
Task get_return_object() {
return Task{
std::coroutine_handle<promise_type>::from_promise(*this)
};
}
std::suspend_never initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_value(int value) { result = value; }
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> handle;
int get() { return handle.promise().result; }
};
// Awaiter for simulated async delay
struct Delay {
int ms;
bool await_ready() { return false; }
void await_suspend(std::coroutine_handle<> h) {
std::thread([=] {
std::this_thread::sleep_for(
std::chrono::milliseconds(ms)
);
h.resume();
}).detach();
}
void await_resume() {}
};
// Async function using co_await
Task fetch_data() {
std::cout << "Starting fetch..." << std::endl;
co_await Delay{100}; // Simulate network delay
std::cout << "Data received!" << std::endl;
co_return 42;
}
int main() {
auto task = fetch_data();
std::this_thread::sleep_for(
std::chrono::milliseconds(200)
);
std::cout << "Result: " << task.get() << std::endl;
return 0;
}

Explanation

The co_await keyword suspends a coroutine until an awaitable completes. This enables writing asynchronous code that reads like synchronous code, without callback hell.

Key Points

  • 1co_await suspends until operation completes
  • 2Awaiter controls suspend/resume behavior
  • 3co_return returns final value
  • 4Enables clean async code