|
1 |
| -# cosched |
| 1 | +# cosched |
| 2 | + |
| 3 | +A simple c++20 coroutine scheduler with only single header. |
| 4 | + |
| 5 | +Let's start from basic examples. |
| 6 | + |
| 7 | +**1. Recursive call** |
| 8 | + |
| 9 | +The following snippet shows a recursive coroutine which calculate fibonacci number in a most naive way. |
| 10 | +We can `co_await` a `task<Tp>` object and get its result. If the current coroutine is running in a scheduler, |
| 11 | +`co_await` will lead an asynchronous invocation, the caller coroutine will be suspended until the callee coroutine finish. |
| 12 | +However, we can also synchronized a coroutine by `task<Tp>::get`, which allows us call a coroutine from a normal function. |
| 13 | +```c++ |
| 14 | +#include "cosched.hpp" |
| 15 | + |
| 16 | +coro::task<int> fibonacci(int n) { |
| 17 | + if (n == 0 || n == 1) { |
| 18 | + co_return n; |
| 19 | + } |
| 20 | + co_return co_await fibonacci(n - 1) + co_await fibonacci(n - 2); |
| 21 | + |
| 22 | +} |
| 23 | + |
| 24 | +int main() { |
| 25 | + coro::task<int> fib = fibonacci(5); |
| 26 | + fib.get(); // result is 5 |
| 27 | +} |
| 28 | +``` |
| 29 | +
|
| 30 | +**2. Run in parallel** |
| 31 | +
|
| 32 | +With a scheduler we can run multiple coroutines simultaneously. |
| 33 | +The following snippet shows a task receives the results from two delayed subtasks. |
| 34 | +Each subtask will spend 1 second to return. And the main task have to wait until both subtasks return their results. |
| 35 | +By scheduling this task with a scheduler that has three worker threads, we can get the final result in one second. |
| 36 | +Because we can have two subtasks run in parallel. |
| 37 | +```c++ |
| 38 | +coro::task<int> slow_response(int a, int b) { |
| 39 | + using namespace std::chrono_literals; |
| 40 | + auto request = [](int v) -> coro::task<int> { |
| 41 | + std::this_thread::sleep_for(1s); |
| 42 | + co_return v; |
| 43 | + }; |
| 44 | + coro::task<int> resp1 = co_await coro::this_scheduler::parallel(request(a)); |
| 45 | + coro::task<int> resp2 = co_await coro::this_scheduler::parallel(request(b)); |
| 46 | + co_return co_await std::move(resp1) + co_await std::move(resp2); |
| 47 | +} |
| 48 | +
|
| 49 | +int main() { |
| 50 | + coro::static_thread_pool pool(3); |
| 51 | + coro::task<int> resp = pool.schedule(slow_response(1, 2)); |
| 52 | + resp.get(); // result is 3 |
| 53 | +} |
| 54 | +``` |
0 commit comments