C++ Library - <coroutine>



The <coroutine> library in C++20, provides the essential building blocks to use coroutines in C++. Coroutines are the modern feature that allows functions to be paused and resumed at certain points. It provides an efficient mechanism for asynchronous programming, generator functions, and cooperative multitasking, making it easier to work with tasks like networking, file I/O.

Unlike traditional functions, coroutines can suspend their execution at certain points and resume later. This is especially useful in scenarios where non-blocking operations(like file I/O or network requests) need to be implemented efficiently.

Including <coroutine> Header

To include the <coroutine> header in your C++ program, you can use the following syntax.

 #include <coroutine> 

Functions of <coroutine> Header

Below is list of all functions from <coroutine> header.

Sr.NoFunctions & Description
1operator=

It assigns the coroutine_handle object.

2operator coroutine_handle<>

It obtains a type-erased coroutine_handle.

3done

It checks if the coroutine has completed.

4operator bool

It checks if the handle represents a coroutine.

5operator() & resume

It resumes execution of the coroutine.

6destroy

It destroys a coroutine.

7promise

It access the promise of a coroutine.

8address

It exports the underlying address.

Generating a Sequence

In the following example, we are going to create a coroutine that generates a sequence of integers.

 #include <iostream> #include <coroutine> struct x { struct promise_type { int a; int b = 0; x get_return_object() { return x { this }; } std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() {} std::suspend_always yield_value(int val) { a = val; return {}; } int getNext() { return b++; } }; promise_type * promise; x(promise_type * p): promise(p) {} int next() { promise -> yield_value(promise -> getNext()); return promise -> a; } }; x generateSequence() { for (int i = 0; i < 4; ++i) { co_yield i; } } int main() { auto sequence = generateSequence(); for (int i = 0; i < 4; ++i) { std::cout << "Next value: " << sequence.next() << '\n'; } return 0; } 

Output

Following is the output of the above code −

 Next value: 0 Next value: 1 Next value: 2 Next value: 3 
Advertisements
close