En bref. Avec les threads, spawn lance le travail tout de suite. Avec async, c’est l’inverse : appeler une async fn ne lance rien. L’appel rend un future, et ce future ne fait rien tant que personne ne l’interroge. Ce modèle explique le bug silencieux le plus courant en Rust asynchrone (une fonction appelée qui ne s’exécute jamais) et les erreurs qu’on rencontre en premier : E0728, E0752, et le E0308 « found future ».
Le modèle en une phrase
Un future est une valeur qui décrit un calcul, pas un calcul en cours. Le créer ne lance rien. C’est
pollqui le fait avancer, jusqu’au prochain.await, et.awaitest la façon normale de demander cepoll.
Si tu viens de JavaScript, c’est le point à désapprendre : une Promise est déjà partie quand tu la reçois, un Future Rust attend qu’on le pousse.
In short. With threads, spawn starts the work right away. With async, it’s the opposite: calling an async fn starts nothing. The call returns a future, and that future does nothing until someone queries it. This model explains the most common silent bug in asynchronous Rust (a function that is called and never runs) and the errors you meet first: E0728, E0752, and the E0308 “found future”.
The model in one sentence
A future is a value that describes a computation, not a computation in progress. Creating it starts nothing.
pollis what makes it advance, up to the next.await, and.awaitis the normal way to ask for thatpoll.
If you come from JavaScript, this is the point to unlearn: a Promise is already running when you receive it, a Rust Future waits to be pushed.
println!("avant");let f = telecharge();println!("future créé");
- Appeler une
async fnn'exécute pas son corps : l'appel rend un future, une valeur qui décrit le calcul. Ici« avant »et« future créé »s'affichent, mais pas« téléchargement lancé ». C'est l'inverse d'une promesse JavaScript, qui démarre dès sa création.Calling anasync fndoesn't run its body: the call returns a future, a value that describes the computation. Here"avant"and"future créé"are printed, but not"téléchargement lancé". It's the opposite of a JavaScript promise, which starts as soon as it is created. - Le bug silencieux : appeler sans
.await. Le future est créé puis détruit aussitôt, sans jamais avoir été exécuté. Le programme affiche« avant »puis« après », et le téléchargement n'a pas eu lieu. Le compilateur ne refuse pas, il avertit.The silent bug: calling without.await. The future is created and dropped right away, without ever running. The program prints"avant"then"après", and the download never happened. The compiler doesn't refuse, it warns. - Autre symptôme : traiter le future comme son résultat.
telecharge()n'est pas unu32, c'est un future qui en produira un. Le compilateur le dit (E0308, « found future ») et propose la correction :.await.Another symptom: treating the future as its result.telecharge()isn't au32, it's a future that will produce one. The compiler says so (E0308, "found future") and suggests the fix:.await. - Pour qu'un future avance, quelqu'un doit l'interroger avec
poll. Dans du code async, c'est.awaitqui s'en charge ; tout en haut, c'est un exécuteur (ici unblock_onde dix lignes). Le corps ne s'exécute qu'à ce moment :« téléchargement lancé »arrive après« future créé ».For a future to make progress, someone has to query it withpoll. In async code,.awaittakes care of it; at the very top, an executor does (here a ten-lineblock_on). The body only runs at that point:"téléchargement lancé"comes after"future créé".
Créer n’est pas lancer
async fn telecharge() -> u32 {
println!(" téléchargement lancé");
42
}
fn main() {
println!("avant");
telecharge();
println!("après");
}warning: unused implementer of `Future` that must be used
--> inerte.rs:8:5
|
8 | telecharge();
| ^^^^^^^^^^^^
|
= note: futures do nothing unless you `.await` or poll them
= note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by defaultLe programme compile, et affiche :
avant
aprèstéléchargement lancé n’apparaît pas. telecharge() a fabriqué un future, personne ne l’a interrogé, et il a été détruit à la fin de l’instruction. Ce n’est qu’un avertissement, pas une erreur : dans une sortie de compilation chargée, il passe facilement inaperçu.
Une async fn est en réalité une fonction ordinaire qui rend un future. Ces deux écritures sont équivalentes :
async fn a() -> u32 {
42
}
fn b() -> impl Future<Output = u32> {
async { 42 }
}Le corps n’est pas « dans » la fonction : il est dans la valeur rendue. Appeler la fonction ne fait que construire cette valeur.
Qui lance le calcul
Le trait Future n’a qu’une méthode :
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
pub enum Poll<T> {
Ready(T),
Pending,
}poll veut dire : « avance autant que tu peux, et dis-moi où tu en es ». Ready(valeur) si c’est terminé, Pending sinon. Un programme qui appelle poll en boucle jusqu’à Ready s’appelle un exécuteur. En voici un minimal, en dix lignes de bibliothèque standard :
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(f: F) -> F::Output {
let mut f = pin!(f);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(v) = f.as_mut().poll(&mut cx) {
return v;
}
}
}Avec lui, le future s’exécute enfin :
fn main() {
println!("avant");
let f = telecharge();
println!("future créé");
let n = block_on(f);
println!("après : {n}");
}avant
future créé
téléchargement lancé
après : 42L’ordre des lignes est la preuve : téléchargement lancé arrive après future créé. C’est le poll qui exécute le corps, pas l’appel.
let f = telecharge(); block_on(f)
┌───────────────────┐ ┌────────────────────────────┐
│ future : inerte │ ─────▶ │ poll ─▶ le corps s'exécute │ ─▶ Ready(42)
└───────────────────┘ └────────────────────────────┘
aucune ligne du corps « téléchargement lancé »Les erreurs autour de .await
Dans du code async, on n’appelle pas poll soi-même : on écrit .await. Mais .await n’est permis que là où une pause est possible.
Hors d’un contexte async : E0728.
fn main() {
let n = telecharge().await;
println!("{n}");
}error[E0728]: `await` is only allowed inside `async` functions and blocks
--> e0728.rs:6:26
|
5 | fn main() {
| --------- this is not `async`
6 | let n = telecharge().await;
| ^^^^^ only allowed inside `async` functions and blocksRendre main async ne suffit pas : E0752.
error[E0752]: `main` function is not allowed to be `async`
--> e0752.rs:5:1
|
5 | async fn main() {
| ^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`Si main rendait un future, qui le pollerait ? La bibliothèque standard ne contient pas d’exécuteur. Il faut en apporter un : le block_on ci-dessus pour comprendre, une bibliothèque comme Tokio pour un vrai programme. #[tokio::main] génère justement une main ordinaire qui appelle block_on.
Prendre le future pour son résultat : E0308.
async fn total() -> u32 {
let n: u32 = telecharge();
n + 1
}error[E0308]: mismatched types
--> e0308.rs:6:18
|
6 | let n: u32 = telecharge();
| --- ^^^^^^^^^^^^ expected `u32`, found future
| |
| expected due to this
|
note: calling an async function returns a future
--> e0308.rs:6:18
|
6 | let n: u32 = telecharge();
| ^^^^^^^^^^^^
help: consider `await`ing on the `Future`
|
6 | let n: u32 = telecharge().await;
| ++++++Ici le compilateur donne à la fois le modèle (« calling an async function returns a future ») et la correction.
Un poll à la fois
Pour voir ce que fait poll, il faut un future qui ne soit pas prêt tout de suite. Pause rend Pending la première fois, Ready la seconde :
struct Pause(bool);
impl Future for Pause {
type Output = ();
fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
if self.0 {
Poll::Ready(())
} else {
self.0 = true;
Poll::Pending
}
}
}
async fn tache() -> u32 {
println!(" étape 1");
Pause(false).await;
println!(" étape 2");
Pause(false).await;
println!(" étape 3");
42
}Interrogeons tache() à la main, trois fois :
let mut f = pin!(tache());
let mut cx = Context::from_waker(Waker::noop());
for i in 1..=3 {
println!("poll n° {i}");
let r = f.as_mut().poll(&mut cx);
println!(" -> {r:?}");
}poll n° 1
étape 1
-> Pending
poll n° 2
étape 2
-> Pending
poll n° 3
étape 3
-> Ready(42)Chaque poll exécute le corps jusqu’au prochain .await qui n’est pas prêt, puis rend la main. Le suivant reprend exactement là.
poll 1 poll 2 poll 3
départ ──────────▶ pause 1 ──────────▶ pause 2 ──────────▶ terminé
étape 1 .await étape 2 .await étape 3 Ready(42)
Pending PendingUn .await est le seul endroit où un async fn peut s’interrompre. Entre deux .await, le code s’exécute d’une traite, comme du code ordinaire.
L’état est rangé dans le future
Pour reprendre « exactement là », il faut se souvenir d’où on en était, et des variables encore utiles. Le compilateur transforme chaque async fn en machine à états : une valeur dont la taille dépend de ce qui doit survivre à une pause.
async fn petit() -> u8 {
1
}
async fn tampon_dans_un_bloc() {
{
let t = [0u8; 1024];
println!(" {}", t.len());
}
Pause(false).await;
}
async fn tampon_a_travers() {
let t = [0u8; 1024];
Pause(false).await;
println!(" {}", t.len());
}petit : 1 octet(s)
tampon_dans_un_bloc : 2 octets
tampon_a_travers : 1026 octetsMesuré avec size_of_val sur les futures, sans les exécuter. Le tableau de 1024 octets qui est encore vivant pendant le .await est stocké dans le future ; celui qui a fini sa vie avant ne l’est pas. Il n’y a pas de pile cachée ni d’allocation : un future est une structure, et sa taille est connue à la compilation.
Deux conséquences de la paresse
L’ordre d’exécution est celui des .await, pas celui des appels.
async fn etape(nom: &str) -> usize {
println!(" {nom} : début");
Pause(false).await;
println!(" {nom} : fin");
nom.len()
}
async fn tout() -> usize {
let a = etape("a");
let b = etape("b");
println!("deux futures créés, rien n'a démarré");
let nb = b.await;
let na = a.await;
na + nb
}deux futures créés, rien n'a démarré
b : début
b : fin
a : début
a : fin
total : 2a est créé en premier et s’exécute en dernier. Et les deux ne s’entremêlent pas : b va jusqu’au bout avant que a ne commence. Créer deux futures ne les fait pas tourner en même temps ; pour cela il faut un outil qui les polle tous les deux, sujet d’un prochain article.
Détruire un future, c’est l’annuler.
async fn tache() {
let _t = Temoin;
println!(" étape 1");
Pause(false).await;
println!(" étape 2 (jamais affichée)");
}On l’interroge une fois, puis on le laisse sortir de portée (Temoin affiche un message dans son Drop) :
étape 1
Pending
on abandonne le future
Temoin détruit
finétape 2 ne s’exécute jamais. Personne n’a « tué » le calcul : on a simplement cessé de le poller, puis détruit la valeur. Les variables qu’elle contenait sont libérées normalement, par la possession.
Ce que l’image cache
- Le
block_onde cet article tourne à vide. Il rappellepollen boucle sans jamais dormir. Un vrai exécuteur utilise leWakerpassé dans leContext: le future le garde, et l’appelle quand il a du nouveau. Mesuré sur un minuteur de 100 ms : 2 polls avec un exécuteur qui dort jusqu’au réveil, plus de 100 000 avec la boucle naïve. - Un future terminé ne se poll plus. Un quatrième
pollsurtache()donne un panic : «async fnresumed after completion »..awaitet les exécuteurs s’arrêtent àReady, donc tu ne le verras que si tu appellespollà la main. Pin. La signature depollprendPin<&mut Self>: la promesse que le future ne sera plus déplacé en mémoire une fois interrogé, parce que son état peut contenir des références vers lui-même.pin!s’en charge ici ; le détail mérite son propre article..awaitenchaîne, il ne parallélise pas.a.await; b.await;exécuteaen entier puisb. La concurrence vient d’ailleurs (join,select,spawnd’un exécuteur).- Un bloc
asyncest paresseux lui aussi.async { ... }fabrique un future sans exécuter son contenu, exactement comme l’appel d’uneasync fn. - Ne bloque pas dans un future. Entre deux
.await, le future garde la main. Unthread::sleepou un calcul long dans unasync fnimmobilise l’exécuteur, et toutes les tâches qu’il devait faire avancer. - Le langage ne fournit que le mécanisme. Le trait
Future,asyncet.awaitsont dans le langage etstd. L’exécuteur, les minuteurs et les entrées-sorties asynchrones viennent d’une bibliothèque.
Pour aller plus loin
- Volume 8, numéro 01 de The Rust Loop, Future & .await, ou le calcul qui ne se lance pas, qui détaille le future inerte et l’analogie à casser avec la promesse JavaScript (lien en bas de page).
- Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599), Result et?(E0277), thiserror et anyhow (E0119), panic et invariants, traits et generics (E0369), dyn et vtable (E0038), règle de l’orphelin (E0117), Box et types récursifs (E0072), Rc et Arc (E0277), Cell et RefCell, threads et move (E0373), Send, Sync etArc<Mutex<T>>(E0277), les canaux mpsc (E0382). - The Rust Book : les fondamentaux de la programmation asynchrone et futures et syntaxe async
- La bibliothèque standard : le trait
FutureetPoll - L’index des erreurs : E0728
Creating is not starting
async fn telecharge() -> u32 {
println!(" téléchargement lancé");
42
}
fn main() {
println!("avant");
telecharge();
println!("après");
}warning: unused implementer of `Future` that must be used
--> inerte.rs:8:5
|
8 | telecharge();
| ^^^^^^^^^^^^
|
= note: futures do nothing unless you `.await` or poll them
= note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by defaultThe program compiles, and prints:
avant
aprèstéléchargement lancé doesn’t show up. telecharge() built a future, nobody queried it, and it was dropped at the end of the statement. It’s only a warning, not an error: in a busy build output, it easily goes unnoticed.
An async fn is really an ordinary function that returns a future. These two spellings are equivalent:
async fn a() -> u32 {
42
}
fn b() -> impl Future<Output = u32> {
async { 42 }
}The body isn’t “in” the function: it’s in the returned value. Calling the function only builds that value.
Who starts the computation
The Future trait has a single method:
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
pub enum Poll<T> {
Ready(T),
Pending,
}poll means: “advance as far as you can, and tell me where you are”. Ready(value) if it’s finished, Pending otherwise. A program that calls poll in a loop until Ready is called an executor. Here is a minimal one, in ten lines of standard library:
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(f: F) -> F::Output {
let mut f = pin!(f);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(v) = f.as_mut().poll(&mut cx) {
return v;
}
}
}With it, the future finally runs:
fn main() {
println!("avant");
let f = telecharge();
println!("future créé");
let n = block_on(f);
println!("après : {n}");
}avant
future créé
téléchargement lancé
après : 42The order of the lines is the proof: téléchargement lancé comes after future créé. The poll runs the body, not the call.
let f = telecharge(); block_on(f)
┌───────────────────┐ ┌────────────────────────────┐
│ future: inert │ ─────▶ │ poll ─▶ the body runs │ ─▶ Ready(42)
└───────────────────┘ └────────────────────────────┘
no line of the body "téléchargement lancé"The errors around .await
In async code, you don’t call poll yourself: you write .await. But .await is only allowed where a pause is possible.
Outside an async context: E0728.
fn main() {
let n = telecharge().await;
println!("{n}");
}error[E0728]: `await` is only allowed inside `async` functions and blocks
--> e0728.rs:6:26
|
5 | fn main() {
| --------- this is not `async`
6 | let n = telecharge().await;
| ^^^^^ only allowed inside `async` functions and blocksMaking main async isn’t enough: E0752.
error[E0752]: `main` function is not allowed to be `async`
--> e0752.rs:5:1
|
5 | async fn main() {
| ^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`If main returned a future, who would poll it? The standard library contains no executor. You have to bring one: the block_on above to understand, a library such as Tokio for a real program. #[tokio::main] precisely generates an ordinary main that calls block_on.
Taking the future for its result: E0308.
async fn total() -> u32 {
let n: u32 = telecharge();
n + 1
}error[E0308]: mismatched types
--> e0308.rs:6:18
|
6 | let n: u32 = telecharge();
| --- ^^^^^^^^^^^^ expected `u32`, found future
| |
| expected due to this
|
note: calling an async function returns a future
--> e0308.rs:6:18
|
6 | let n: u32 = telecharge();
| ^^^^^^^^^^^^
help: consider `await`ing on the `Future`
|
6 | let n: u32 = telecharge().await;
| ++++++Here the compiler gives both the model (“calling an async function returns a future”) and the fix.
One poll at a time
To see what poll does, you need a future that isn’t ready right away. Pause returns Pending the first time, Ready the second:
struct Pause(bool);
impl Future for Pause {
type Output = ();
fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
if self.0 {
Poll::Ready(())
} else {
self.0 = true;
Poll::Pending
}
}
}
async fn tache() -> u32 {
println!(" étape 1");
Pause(false).await;
println!(" étape 2");
Pause(false).await;
println!(" étape 3");
42
}Let’s query tache() by hand, three times:
let mut f = pin!(tache());
let mut cx = Context::from_waker(Waker::noop());
for i in 1..=3 {
println!("poll n° {i}");
let r = f.as_mut().poll(&mut cx);
println!(" -> {r:?}");
}poll n° 1
étape 1
-> Pending
poll n° 2
étape 2
-> Pending
poll n° 3
étape 3
-> Ready(42)Each poll runs the body up to the next .await that isn’t ready, then yields. The next one resumes exactly there.
poll 1 poll 2 poll 3
start ──────────▶ pause 1 ──────────▶ pause 2 ──────────▶ done
étape 1 .await étape 2 .await étape 3 Ready(42)
Pending PendingAn .await is the only place where an async fn can be interrupted. Between two .await, the code runs straight through, like ordinary code.
The state is stored in the future
To resume “exactly there”, you have to remember where you were, and the variables still needed. The compiler turns every async fn into a state machine: a value whose size depends on what must survive a pause.
async fn petit() -> u8 {
1
}
async fn tampon_dans_un_bloc() {
{
let t = [0u8; 1024];
println!(" {}", t.len());
}
Pause(false).await;
}
async fn tampon_a_travers() {
let t = [0u8; 1024];
Pause(false).await;
println!(" {}", t.len());
}petit : 1 octet(s)
tampon_dans_un_bloc : 2 octets
tampon_a_travers : 1026 octetsMeasured with size_of_val on the futures, without running them. The 1024-byte array that is still alive during the .await is stored in the future; the one whose life ended before is not. There is no hidden stack and no allocation: a future is a struct, and its size is known at compile time.
Two consequences of laziness
Execution order is the order of the .await, not of the calls.
async fn etape(nom: &str) -> usize {
println!(" {nom} : début");
Pause(false).await;
println!(" {nom} : fin");
nom.len()
}
async fn tout() -> usize {
let a = etape("a");
let b = etape("b");
println!("deux futures créés, rien n'a démarré");
let nb = b.await;
let na = a.await;
na + nb
}deux futures créés, rien n'a démarré
b : début
b : fin
a : début
a : fin
total : 2a is created first and runs last. And the two don’t interleave: b goes all the way before a begins. Creating two futures doesn’t make them run at the same time; for that you need a tool that polls both, the topic of an upcoming article.
Dropping a future cancels it.
async fn tache() {
let _t = Temoin;
println!(" étape 1");
Pause(false).await;
println!(" étape 2 (jamais affichée)");
}We query it once, then let it go out of scope (Temoin prints a message in its Drop):
étape 1
Pending
on abandonne le future
Temoin détruit
finétape 2 never runs. Nobody “killed” the computation: we simply stopped polling it, then dropped the value. The variables it contained are freed normally, through ownership.
What the picture hides
- This article’s
block_onspins. It callspollagain in a loop without ever sleeping. A real executor uses theWakerpassed in theContext: the future keeps it, and calls it when it has news. Measured on a 100 ms timer: 2 polls with an executor that sleeps until woken, more than 100,000 with the naive loop. - A finished future is not polled again. A fourth
pollontache()gives a panic: “async fnresumed after completion”..awaitand executors stop atReady, so you’ll only see it if you callpollby hand. Pin. The signature ofpolltakesPin<&mut Self>: the promise that the future won’t be moved in memory once polled, because its state may contain references to itself.pin!handles it here; the detail deserves its own article..awaitsequences, it doesn’t parallelise.a.await; b.await;runsaentirely and thenb. Concurrency comes from elsewhere (join,select, an executor’sspawn).- An
asyncblock is lazy too.async { ... }builds a future without running its content, exactly like calling anasync fn. - Don’t block inside a future. Between two
.await, the future keeps control. Athread::sleepor a long computation in anasync fnfreezes the executor, and every task it was supposed to advance. - The language only provides the mechanism. The
Futuretrait,asyncand.awaitare in the language andstd. The executor, timers and asynchronous I/O come from a library.
Going further
- Volume 8, issue 01 of The Rust Loop, Future & .await, or the computation that doesn’t start, which details the inert future and the analogy to break with the JavaScript promise (link at the bottom of the page).
- Previous articles: move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277), thiserror and anyhow (E0119), panic and invariants, traits and generics (E0369), dyn and the vtable (E0038), the orphan rule (E0117), Box and recursive types (E0072), Rc and Arc (E0277), Cell and RefCell, threads and move (E0373), Send, Sync andArc<Mutex<T>>(E0277), mpsc channels (E0382). - The Rust Book: fundamentals of asynchronous programming and futures and the async syntax
- The standard library: the
Futuretrait andPoll - The error index: E0728