Debian Codegraph @

third_party/rust/async-task/README.md

raw
1 # async-task
2
3 [![Build](https://github.com/smol-rs/async-task/workflows/Build%20and%20test/badge.svg)](
4 https://github.com/smol-rs/async-task/actions)
5 [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](
6 https://github.com/smol-rs/async-task)
7 [![Cargo](https://img.shields.io/crates/v/async-task.svg)](
8 https://crates.io/crates/async-task)
9 [![Documentation](https://docs.rs/async-task/badge.svg)](
10 https://docs.rs/async-task)
11
12 Task abstraction for building executors.
13
14 To spawn a future onto an executor, we first need to allocate it on the heap and keep some
15 state attached to it. The state indicates whether the future is ready for polling, waiting to
16 be woken up, or completed. Such a stateful future is called a *task*.
17
18 All executors have a queue that holds scheduled tasks:
19
20 ```rust
21 let (sender, receiver) = flume::unbounded();
22 ```
23
24 A task is created using either `spawn()`, `spawn_local()`, or `spawn_unchecked()` which
25 return a `Runnable` and a `Task`:
26
27 ```rust
28 // A future that will be spawned.
29 let future = async { 1 + 2 };
30
31 // A function that schedules the task when it gets woken up.
32 let schedule = move |runnable| sender.send(runnable).unwrap();
33
34 // Construct a task.
35 let (runnable, task) = async_task::spawn(future, schedule);
36
37 // Push the task into the queue by invoking its schedule function.
38 runnable.schedule();
39 ```
40
41 The `Runnable` is used to poll the task's future, and the `Task` is used to await its
42 output.
43
44 Finally, we need a loop that takes scheduled tasks from the queue and runs them:
45
46 ```rust
47 for runnable in receiver {
48 runnable.run();
49 }
50 ```
51
52 Method `run()` polls the task's future once. Then, the `Runnable`
53 vanishes and only reappears when its `Waker` wakes the task, thus
54 scheduling it to be run again.
55
56 ## License
57
58 Licensed under either of
59
60 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
61 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
62
63 at your option.
64
65 #### Contribution
66
67 Unless you explicitly state otherwise, any contribution intentionally submitted
68 for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
69 dual licensed as above, without any additional terms or conditions.