@@ -6,6 +6,38 @@ author: loongs-zhang
66
77# Coroutine Overview
88
9+ ## Usage
10+
11+ ``` rust
12+ use open_coroutine_core :: common :: constants :: CoroutineState ;
13+ use open_coroutine_core :: coroutine :: Coroutine ;
14+
15+ fn main () -> std :: io :: Result <()> {
16+ let mut co = Coroutine :: new (
17+ // optional coroutine name
18+ None ,
19+ | suspender , input | {
20+ assert_eq! (1 , input );
21+ assert_eq! (3 , suspender . suspend_with (2 ));
22+ 4
23+ },
24+ // optional stack size
25+ None ,
26+ // optional coroutine priority
27+ None ,
28+ )? ;
29+ // Macro `co!` is equivalent to the code above
30+ // let mut co = open_coroutine_core::co!(|suspender, input| {
31+ // assert_eq!(1, input);
32+ // assert_eq!(3, suspender.suspend_with(2));
33+ // 4
34+ // })?;
35+ assert_eq! (CoroutineState :: Suspend (2 , 0 ), co . resume_with (1 )? );
36+ assert_eq! (CoroutineState :: Complete (4 ), co . resume_with (3 )? );
37+ Ok (())
38+ }
39+ ```
40+
941## What is coroutine?
1042
1143A [ coroutine] ( https://en.wikipedia.org/wiki/Coroutine ) is a function that can be paused and resumed, yielding values to
@@ -15,6 +47,26 @@ resumed.
1547
1648The above is excerpted from [ corosensei] ( https://github.com/Amanieu/corosensei ) .
1749
50+ ## Coroutine VS Thread
51+
52+ | | coroutine | thread |
53+ | -------------------| -----------| ---------|
54+ | switch efficiency | ✅ Higher | ❌ High |
55+ | memory efficiency | KB/MB | KB/MB |
56+ | scheduled by OS | ❌ | ✅ |
57+ | stack grow | ✅ | ❌ |
58+
59+ ## Stackfull VS Stackless
60+
61+ | | stackfull | stackless |
62+ | -------------------| -----------| -----------|
63+ | switch efficiency | ❌ High | ✅ Higher |
64+ | memory efficiency | ❌ KB/MB | ✅ Bytes |
65+ | limitations | ✅ Few | ❌ Many |
66+
67+ In general, if the requirements for resource utilization and switching performance are not very strict, using a
68+ stackfull approach would be more convenient and the code would be easier to maintain.
69+
1870## State in open-coroutine
1971
2072``` text
0 commit comments