Skip to content

Commit ec35ba0

Browse files
committed
add readme
1 parent b6b89b3 commit ec35ba0

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed

README.md

+54-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,54 @@
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+
```

test.cc

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ coro::task<int> slow_response(int a, int b) {
4545
};
4646
coro::task<int> resp1 = co_await coro::this_scheduler::parallel(request(a));
4747
coro::task<int> resp2 = co_await coro::this_scheduler::parallel(request(b));
48-
std::this_thread::sleep_for(1s);
48+
// std::this_thread::sleep_for(1s);
4949
co_return co_await std::move(resp1) + co_await std::move(resp2);
5050
}
5151

0 commit comments

Comments
 (0)