| 1 | Title: Task Groups |
| 2 | |
| 3 | # Task Groups |
| 4 | |
| 5 | `DexTaskGroup` provides a structured scope for related futures. |
| 6 | |
| 7 | Task groups track existing [[email protected]] instances as a synthetic scope. |
| 8 | The task group can track various futures and then be closed. If the task |
| 9 | group is cancelled, all tasks within the group are cancelled. |
| 10 | |
| 11 | Tasks groups can be composed of additional task groups as they are themselves a |
| 12 | [[email protected]]. |
| 13 | |
| 14 | ## Core Rules |
| 15 | |
| 16 | - Add futures explicitly with [[email protected]]. |
| 17 | - Call [[email protected]] when no more futures should be added. |
| 18 | - Call [[email protected]] to force cancellation of all tracked |
| 19 | children. |
| 20 | - The group itself is a [[email protected]] and can be awaited. |
| 21 | |
| 22 | ## Cancellation |
| 23 | |
| 24 | Task group cancellation is stronger than ordinary discard-driven cancellation. |
| 25 | |
| 26 | Libdex futures already use discard as an escape hatch when the last observer |
| 27 | goes away. That remains unchanged. A task group can also force cancellation of |
| 28 | its tracked futures even if they are still referenced elsewhere. |
| 29 | |
| 30 | To make this safe, futures that are cancelled by a task group are completed |
| 31 | with cancellation before any later resolve/reject attempt can take effect. |
| 32 | Subsequent completion attempts are ignored. |
| 33 | |
| 34 | This is the mechanism that lets child code keep running briefly without being |
| 35 | able to resurrect a cancelled future. |
| 36 | |
| 37 | ## Disowning Futures |
| 38 | |
| 39 | [[email protected]] still means "do not cancel this work just because |
| 40 | observers disappeared." |
| 41 | |
| 42 | It does not override task-group ownership. If a future is part of a task |
| 43 | group, the group may still cancel it directly. |
| 44 | |
| 45 | That keeps the two concepts separate: |
| 46 | |
| 47 | - `disown` is about observer interest. |
| 48 | - task groups are about structured ownership. |
| 49 | |
| 50 | ## Thread Default Groups |
| 51 | |
| 52 | Task groups can be pushed as the thread-default group using |
| 53 | [[email protected]_thread_default] and later restored with |
| 54 | [[email protected]_thread_default]. |
| 55 | |
| 56 | This is a convenience layer for callers of [[email protected]]. |
| 57 | You can pass `null` for the group and it will automatically use the |
| 58 | thread default. |
| 59 | |
| 60 | ## Example |
| 61 | |
| 62 | ```c |
| 63 | DexTaskGroup *group = dex_task_group_new (); |
| 64 | DexFuture *group_future; |
| 65 | |
| 66 | dex_task_group_add (group, load_config ()); |
| 67 | dex_task_group_add (group, refresh_cache ()); |
| 68 | |
| 69 | group_future = dex_task_group_close (group); |
| 70 | |
| 71 | if (!dex_await_boolean (group_future, &error)) |
| 72 | ... |
| 73 | ``` |