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