Debian Codegraph @

docs/coroutines.md

raw symbols SCIP
1 Title: Stackless Coroutines
2
3 # Stackless Coroutines
4
5 Libdex supports two coroutine-like execution models:
6
7 * [[email protected]] for stackful execution with its own stack.
8 * [[email protected]] for stackless execution using an explicit state machine.
9
10 [[email protected]] is a [[email protected]] that runs on a [[email protected]].
11 Use it when you want linear async-style flow without paying for a full fiber stack.
12
13 ## When To Use This Over a Fiber
14
15 Use a coroutine when all of these are true:
16
17 * The task is mostly "then/await-like" and spends most of its time waiting for futures.
18 * You want low-overhead scheduling and smaller per-task memory footprint.
19 * You are comfortable with explicit resume-state style code.
20
21 Prefer a [[email protected]] when:
22
23 * You need deep call stacks, existing recursive control flow, or
24 third-party functions that expect normal stackful execution.
25
26 ## How to Run A Coroutine
27
28 Use [[email protected]_coroutine] to schedule a coroutine.
29
30 ```c
31 DexFuture *
32 my_coroutine (DexCoroutineContext *context,
33 gpointer user_data)
34 {
35 DEX_COROUTINE_BEGIN (context);
36
37 /* return a future when done */
38 return dex_future_new_true ();
39
40 DEX_COROUTINE_END;
41 }
42
43 DexFuture *future =
44 dex_scheduler_spawn_coroutine (NULL,
45 my_coroutine,
46 user_data,
47 user_data_destroy);
48 ```
49
50 If `scheduler` is `NULL`, the default scheduler is used.
51
52 ## The Function Contract
53
54 Coroutine entrypoints use [[email protected]]:
55
56 * Return a [[email protected]] to complete.
57 * Return `NULL` only to indicate that the coroutine is suspended.
58 * Store any state you need in the provided `user_data`.
59
60 The recommended pattern is:
61
62 * define any state as a small struct (or with `DEX_DEFINE_CLOSURE_TYPE`);
63 * call `DEX_COROUTINE_BEGIN` at the start;
64 * call `DEX_COROUTINE_SUSPEND` when you only need to wait for completion;
65 * call `DEX_COROUTINE_SUSPEND_*` for each awaited step;
66 * return a future at completion;
67 * end with `DEX_COROUTINE_END`.
68
69 ## Waiting on Futures Correctly
70
71 Use `DEX_COROUTINE_SUSPEND_BOOLEAN` and related macros instead of calling
72 `dex_await_*()` directly.
73
74 `dex_await_*()` is a fiber-first API and in practice cannot be used like normal
75 code unless the future is already done. Coroutine suspend helpers:
76
77 * save the awaited future in the coroutine state;
78 * return `NULL` to yield;
79 * resume execution only after that future settles;
80 * extract the awaited value on resume.
81
82 Use `DEX_COROUTINE_SUSPEND` when you only need to wait for a future to
83 finish and do not need its result. This is the coroutine-friendly replacement
84 for `dex_await (future, NULL)`.
85
86 These macros are available for common await types:
87
88 * `DEX_COROUTINE_SUSPEND`
89 * `DEX_COROUTINE_SUSPEND_BOOLEAN`
90 * `DEX_COROUTINE_SUSPEND_INT`, `DEX_COROUTINE_SUSPEND_UINT`
91 * `DEX_COROUTINE_SUSPEND_INT64`, `DEX_COROUTINE_SUSPEND_UINT64`
92 * `DEX_COROUTINE_SUSPEND_OBJECT`, `DEX_COROUTINE_SUSPEND_BOXED`
93 * `DEX_COROUTINE_SUSPEND_POINTER`
94 * `DEX_COROUTINE_SUSPEND_ENUM`, `DEX_COROUTINE_SUSPEND_FLAGS`
95 * `DEX_COROUTINE_SUSPEND_DOUBLE`, `DEX_COROUTINE_SUSPEND_FLOAT`
96
97 ## Common Correctness Pattern
98
99 Keep coroutine state explicit.
100
101 `DEX_COROUTINE_SUSPEND_*` assumes the state machine stores both the continuation
102 label and the currently pending future. A typical helper is:
103
104 ```c
105 DEX_DEFINE_CLOSURE_TYPE (LoadState, load_state,
106 DEX_DEFINE_CLOSURE_OBJECT (GFile, file),
107 DEX_DEFINE_CLOSURE_OBJECT (GFileInputStream, input),
108 DEX_DEFINE_CLOSURE_OBJECT (GFileInfo, info),
109 DEX_DEFINE_CLOSURE_VALUE (int, io_priority))
110
111 static DexFuture *
112 load_with_cache (DexCoroutineContext *context,
113 gpointer user_data)
114 {
115 LoadState *state = user_data;
116 g_autoptr(GError) error = NULL;
117
118 DEX_COROUTINE_BEGIN (context);
119
120 DEX_COROUTINE_SUSPEND_OBJECT (&state->input, &error,
121 dex_file_read (state->file, state->io_priority));
122 if (error != NULL)
123 return dex_future_new_for_error (g_steal_pointer (&error));
124
125 DEX_COROUTINE_SUSPEND_OBJECT (&state->info, &error,
126 dex_file_input_stream_query_info (state->input,
127 G_FILE_ATTRIBUTE_STANDARD_SIZE,
128 state->io_priority));
129 if (error != NULL)
130 return dex_future_new_for_error (g_steal_pointer (&error));
131
132 return dex_future_new_int64 (g_file_info_get_size (state->info));
133
134 DEX_COROUTINE_END;
135 }
136 ```
137
138 Use `DEX_DEFINE_CLOSURE_VALUE_WITH_CLEAR()` for inline value types that need
139 address-based cleanup, such as `GWeakRef`:
140
141 ```c
142 DEX_DEFINE_CLOSURE_TYPE (WatchState, watch_state,
143 DEX_DEFINE_CLOSURE_VALUE_WITH_CLEAR (GWeakRef,
144 widget_ref,
145 g_weak_ref_clear))
146 ```
147
148 ## Cleanup And Cancellation
149
150 Like all `DexFuture` values, coroutines follow normal ownership and cancellation
151 rules.
152
153 * If a coroutine is no longer depended on, discarding may cancel its work.
154 * Cancellation will propagate into an error for suspended coroutines which
155 they can handle when they are next resumed.
156 * If work must complete even after callers drop references, use
157 [[email protected]] on the returned future.
158 * State registered with the coroutine is released with the configured
159 callback function when the [[email protected]] completes.
160
161 ## When Not To Use
162
163 Do not use coroutines for arbitrary synchronous or blocking loops.
164 Blocking work should be offloaded with [[email protected]_spawn] or [[email protected]].
165
166 ## Related Pages
167
168 * [Coroutines API reference](coroutines.html)
169 * [Scheduler behavior and pinning](schedulers.html)