Request Short Link
C++ 98
C++ 11
C++ 14
C++ 17
C++ 20
C++ 23
C++ 2c
for-loops as while-loops
array subscription
Show all implicit casts
Show all template parameters of a CallExpr
Use libc++
Transform std::initializer_list
Show noexcept internals
Show padding information
Show coroutine transformation
Show C++ to C transformation
Show object lifetime
Default
15
18
20
22
26
More
GitHub
Patreon
Issues
About
Policies
Examples
C++ Insights @ YouTube
Settings
Version
Join now: C++ Self Study + 1:1 Coaching
×
Made by
Andreas Fertig
Powered by
Flask
and
CodeMirror
Source:
#include <coroutine> #include <exception> // std::terminate #include <iostream> #include <list> #include <new> #include <utility> struct Task { struct promise_type { Task get_return_object() noexcept { return {}; } std::suspend_never initial_suspend() noexcept { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void unhandled_exception() {} }; }; struct Scheduler { std::list<std::coroutine_handle<>> _tasks{}; bool schedule() { auto task = _tasks.front(); _tasks.pop_front(); if(not task.done()) { task.resume(); } return not _tasks.empty(); } auto suspend() { struct awaiter : std::suspend_always { Scheduler& _sched; explicit awaiter(Scheduler& sched) : _sched{sched} {} void await_suspend(std::coroutine_handle<> coro) const noexcept { _sched._tasks.push_back(coro); } }; return awaiter{*this}; } }; Task taskA(Scheduler& sched) { std::cout << "Hello, from task A\n"; co_await sched.suspend(); std::cout << "a is back doing work\n"; co_await sched.suspend(); std::cout << "a is back doing more work\n"; } Task taskB(Scheduler& sched) { std::cout << "Hello, from task B\n"; co_await sched.suspend(); std::cout << "b is back doing work\n"; co_await sched.suspend(); std::cout << "b is back doing more work\n"; } int main() { Scheduler scheduler{}; taskA(scheduler); taskB(scheduler); while(scheduler.schedule()) {} }
Insight:
Console: