How do I build a simple task scheduler using coroutines in C++?

Building a simple task scheduler using coroutines in C++ can significantly enhance the way we manage asynchronous tasks. This example shows how to create a basic task scheduler that leverages C++20 coroutines.

#include 
#include 
#include 
#include 

class Task {
public:
    struct promise_type {
        Task get_return_object() {
            return Task(this);
        }
        std::suspend_never initial_suspend() { return {}; }
        std::suspend_never final_suspend() noexcept { return {}; }
        void unhandled_exception() { std::terminate(); }
        void return_void() {}
    };

    Task(promise_type* p) : handle(p) {}
    ~Task() { handle.destroy(); }

private:
    std::coroutine_handle handle;
};

class TaskScheduler {
public:
    void schedule(Task task) {
        tasks.push(std::move(task));
    }

    void run() {
        while (!tasks.empty()) {
            auto task = std::move(tasks.front());
            tasks.pop();
            task.resume();
        }
    }

private:
    std::queue tasks;
};

// Example coroutine to be scheduled
Task myTask() {
    std::cout << "Task is running...\n";
    co_return;
}

int main() {
    TaskScheduler scheduler;
    scheduler.schedule(myTask());
    scheduler.run();
    return 0;
}
    

coroutines C++ task scheduler async programming C++20 concurrency