What are Coroutines?
A Coroutine is a function that can suspend its execution and be resumed later. Unlike regular functions (which run until they return or throw), coroutines can "pause" their state, return control to the caller, and pick up exactly where they left off.
In C++, coroutines are stackless, meaning they don't have their own call stack, making them extremely lightweight.
1. The Three New Keywords
co_yield: Suspends execution and returns a value to the caller (used for Generators).co_await: Suspends execution until an asynchronous task is complete.co_return: Finishes the coroutine and returns a final result.
2. Example: A Simple Generator
Generators allow you to produce values lazily. You can define an infinite sequence without using infinite memory.
cpp
3. Asynchronous Tasks
Coroutines are the foundation for high-performance networking and I/O. Instead of using callbacks or threads, you can "await" a result.
cpp
4. Why use Coroutines?
- Efficiency: Millions of coroutines can run on a single thread.
- Readability: Asynchronous code looks like clean, sequential synchronous code.
- State Management: The compiler handles saving and restoring local variables for you.
- No Overhead: No context switching between OS threads.
Summary Checklist
- Coroutines are functions that can pause (
co_yield/co_await). - They are stackless and extremely memory-efficient.
- Perfect for Generators (lazy sequences) and Async I/O.
- The compiler generates the state-saving code for you.
- Use
co_returnto finish the execution.