Coroutines in C++

 Coroutines in C++


Coroutines are a new feature introduced in C++20 that allow for cooperative multitasking and asynchronous programming. They provide a way to write code that can be suspended and resumed, enabling the creation of asynchronous operations without resorting to callback functions or explicit state machines. Here's an example demonstrating the usage of coroutines:


#include <iostream>

#include <experimental/coroutine>


struct MyCoroutine {

    struct promise_type {

        int current_value;


        MyCoroutine get_return_object() {

            return MyCoroutine(std::experimental::coroutine_handle<promise_type>::from_promise(*this));

        }


        std::experimental::suspend_always initial_suspend() {

            return {};

        }


        std::experimental::suspend_always final_suspend() {

            return {};

        }


        void return_void() {}


        std::experimental::suspend_always yield_value(int value) {

            current_value = value;

            return {};

        }


        void unhandled_exception() {

            std::terminate();

        }

    };


    std::experimental::coroutine_handle<promise_type> coroutine;


    explicit MyCoroutine(std::experimental::coroutine_handle<promise_type> coroutine)

        : coroutine(coroutine) {}


    ~MyCoroutine() {

        if (coroutine)

            coroutine.destroy();

    }


    bool move_next() {

        coroutine.resume();

        return !coroutine.done();

    }


    int current_value() const {

        return coroutine.promise().current_value;

    }

};


MyCoroutine generate_numbers(int start, int end) {

    for (int i = start; i <= end; ++i) {

        co_yield i;

    }

}


int main() {

    MyCoroutine coroutine = generate_numbers(1, 5);


    while (coroutine.move_next()) {

        std::cout << coroutine.current_value() << " ";

    }

    std::cout << std::endl;


    return 0;

}

In the above code, we define a coroutine named MyCoroutine. It has a nested promise_type struct that is responsible for managing the coroutine's state. The promise_type defines several coroutine-related functions, such as initial_suspend(), final_suspend(), yield_value(), and return_void().


The generate_numbers() function is a coroutine that uses the co_yield keyword to suspend and resume its execution. It yields a sequence of numbers from start to end.


In the main() function, we create an instance of MyCoroutine using generate_numbers() with a range of numbers from 1 to 5. We then use a while loop to iterate over the coroutine, calling move_next() to resume the coroutine's execution and current_value() to retrieve the current value yielded by the coroutine. We print each value until the coroutine is done.


Coroutines provide a powerful mechanism for writing asynchronous code that is more readable and less error-prone compared to traditional callback-based approaches.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...