En bref. En Rust async, il n’y a pas de mécanisme d’annulation à part : annuler un future, c’est le détruire. select! et timeout ne font rien d’autre, et tout ce qui surprend dans l’annulation vient de là. Le code après le .await ne s’exécute jamais, le Drop s’exécute quand même, et ce que le future avait déjà pris part avec lui.
Le modèle en une phrase
Un future n’avance que si on le polle, et il ne s’arrête qu’à un
.await. L’annuler, c’est le détruire pendant qu’il est arrêté là :select!garde le premier future prêt et détruit les autres, et chacun emporte tout ce qu’il contenait.
C’est la suite directe de l’article sur Future et .await : un future est une valeur, et une valeur qu’on détruit ne fait plus rien.
In short. In async Rust, there is no separate cancellation mechanism: cancelling a future means dropping it. select! and timeout do nothing else, and everything surprising about cancellation comes from that. The code after the .await never runs, Drop runs anyway, and whatever the future had already taken goes with it.
The model in one sentence
A future only advances when it is polled, and it only stops at an
.await. Cancelling it means dropping it while it is stopped there:select!keeps the first future ready and drops the others, and each one takes everything it contained with it.
It follows directly from the article on Future and .await: a future is a value, and a value you drop does nothing more.
let gagnant = tokio::select! {v = lent() => v,_ = sleep(Duration::from_millis(150)) => "minuteur",};
select!reçoit deux futures :lent(), qui fait trois étapes de 100 ms, et un minuteur de 150 ms. Il les polle tous les deux dans la même tâche.lentaffiche« étape 1 »et s'arrête à son premier.await; le minuteur n'est pas prêt non plus.select!receives two futures:lent(), which does three 100 ms steps, and a 150 ms timer. It polls both in the same task.lentprints"étape 1"and stops at its first.await; the timer isn't ready either.- À 100 ms, le minuteur interne de
lentse réveille :select!le repolle, il affiche« étape 2 »et se remet en pause. Les deux futures avancent tour à tour, chacun jusqu'à son prochain.await. Personne n'a encore gagné.At 100 ms, the timer insidelentwakes up:select!polls it again, it prints"étape 2"and pauses again. The two futures advance in turn, each up to its next.await. Nobody has won yet. - À 150 ms, le minuteur est prêt : sa branche gagne.
select!détruit alors l'autre future, là où il était en pause.lentne reprendra jamais :« étape 3 »ne s'affiche pas. Mais ses variables sont libérées normalement, et leDropde son témoin s'exécute.At 150 ms, the timer is ready: its branch wins.select!then drops the other future, right where it was paused.lentwill never resume:"étape 3"isn't printed. But its variables are freed normally, and its witness'sDropruns. timeoutn'est rien d'autre que cette course, emballée : le future contre un minuteur. Si le minuteur gagne, le future est détruit de la même façon et tu reçoisErr(Elapsed), qui s'affiche deadline has elapsed.timeoutis nothing but that race, wrapped up: the future against a timer. If the timer wins, the future is dropped the same way and you getErr(Elapsed), which prints as deadline has elapsed.
select! : une course
Un future lent, qui fait trois étapes de 100 ms, et un témoin qui signale sa destruction :
struct Temoin(&'static str);
impl Drop for Temoin {
fn drop(&mut self) {
println!(" {} : détruit", self.0);
}
}
async fn lent() -> &'static str {
let _t = Temoin("lent");
for i in 1..=3 {
println!(" lent : étape {i}");
sleep(Duration::from_millis(100)).await;
}
"lent"
}
#[tokio::main]
async fn main() {
let gagnant = tokio::select! {
v = lent() => v,
_ = sleep(Duration::from_millis(150)) => "minuteur",
};
println!("gagnant : {gagnant}");
} lent : étape 1
lent : étape 2
lent : détruit
gagnant : minuteurselect! polle ses deux futures dans la même tâche, sans thread supplémentaire. Chacun avance jusqu’à son prochain .await. Le premier qui est prêt gagne ; l’autre est détruit.
0 ms 100 ms 150 ms 200 ms 300 ms
lent() ├─ étape 1 ──┼─ étape 2 ─╳ ░░░░░░░░░░░░░░░░░░░ détruit à son .await
sleep ├────────────────────────▶ prêt : sa branche gagneTrois choses à lire dans cette sortie :
étape 3ne s’affiche jamais.lentétait en pause dans son secondsleep; personne ne le repollera.lent : détruits’affiche. Détruire un future, c’est détruire ses variables locales, donc_t. Le nettoyage parDropfonctionne aussi pour un future annulé.lentn’a rien fait pour être annulable. Tout future l’est, à chacun de ses.await.
timeout : la même course, emballée
match timeout(Duration::from_millis(150), lent()).await {
Ok(v) => println!("terminé : {v}"),
Err(e) => println!("{e}"),
}
match timeout(Duration::from_millis(500), lent()).await {
Ok(v) => println!("terminé : {v}"),
Err(e) => println!("{e}"),
} lent : étape 1
lent : étape 2
lent : détruit
deadline has elapsed
lent : étape 1
lent : étape 2
lent : étape 3
lent : détruit
terminé : lenttimeout fait courir un future contre un minuteur. Si le minuteur gagne, le future est détruit et tu reçois Err(Elapsed), dont l’affichage est deadline has elapsed. Ce n’est pas un panic : c’est un Result ordinaire, à traiter avec match ou ?. Avec 500 ms, le future finit à temps, et son témoin est détruit normalement, à la fin de la fonction.
join! attend tout, select! attend le premier
async fn etape(nom: &'static str, ms: u64) -> &'static str {
sleep(Duration::from_millis(ms)).await;
println!(" {nom} : fini");
nom
}
let (a, b) = tokio::join!(etape("a", 100), etape("b", 200));
// puis
let g = tokio::select! {
v = etape("a", 100) => v,
v = etape("b", 200) => v,
}; a : fini
b : fini
join! : a et b, 200 ms environ
a : fini
select! : a seul, 100 ms environLes deux macros pollent plusieurs futures dans une seule tâche. join! continue jusqu’à ce que tous aient fini et rend toutes les valeurs. select! s’arrête au premier, et b : fini ne s’affiche pas : b a été détruit à mi-chemin.
| attend | rend | les autres futures | |
|---|---|---|---|
join! | tous | toutes les valeurs | vont au bout |
select! | le premier prêt | une valeur | sont détruits |
Une tâche lancée n’appartient plus à celui qui la lance
Jusqu’ici, détruire le future suffisait. Avec tokio::spawn, la règle change : la tâche est confiée au runtime, et le JoinHandle n’est qu’un moyen de la suivre.
println!("drop du JoinHandle :");
let h = tokio::spawn(tache("a"));
sleep(Duration::from_millis(150)).await;
drop(h);
println!(" handle détruit");
sleep(Duration::from_millis(250)).await;
println!("abort :");
let h = tokio::spawn(tache("b"));
sleep(Duration::from_millis(150)).await;
h.abort();
match h.await {
Ok(v) => println!(" résultat : {v}"),
Err(e) => println!(" erreur : {e} (is_cancelled : {})", e.is_cancelled()),
}tache est le même future en trois étapes que lent, avec un nom.
drop du JoinHandle :
a : étape 1
a : étape 2
handle détruit
a : étape 3
a : détruit
abort :
b : étape 1
b : étape 2
b : détruit
erreur : task 12 was cancelled (is_cancelled : true)Détruire le JoinHandle détache la tâche : a va jusqu’à l’étape 3, et son résultat est perdu. Pour l’annuler il faut le demander, avec abort(). La tâche b est alors détruite à son prochain .await, et l’attendre rend une JoinError (le numéro de tâche varie d’une exécution à l’autre).
future attendu directement tâche lancée avec spawn
┌──────────────┐ ┌──────────────┐ ┌──────────┐
│ select! │ possède │ JoinHandle │ suit │ runtime │ possède
│ timeout ├───▶ future │ ├─ ─ ─▶│ ├───▶ tâche
└──────────────┘ └──────────────┘ └──────────┘
détruire = annuler détruire = détacher ; abort() = annulerL’annulation n’arrive qu’à un .await
let h = tokio::spawn(async {
println!(" calcul : début");
std::thread::sleep(Duration::from_millis(300));
println!(" calcul : fin");
42
});
sleep(Duration::from_millis(100)).await;
h.abort();
println!("abort demandé");
match h.await {
Ok(v) => println!("résultat : {v}"),
Err(e) => println!("erreur : {e}"),
} calcul : début
abort demandé
calcul : fin
résultat : 42abort est demandé à 100 ms, en plein calcul. La tâche termine quand même et rend 42. Elle ne contient aucun .await : il n’y a aucun endroit où elle est arrêtée, donc aucun endroit où la détruire. C’est le même fait que dans l’article sur les fonctions colorées : entre deux .await, un future ne rend pas la main. Un timeout autour d’un appel bloquant n’expire pas plus tôt, pour la même raison.
Ce que l’annulation emporte
Voici le piège. Une fonction qui lit deux messages d’un canal, et une boucle qui l’attend en affichant un « tic » toutes les 70 ms de silence :
async fn lire_paire(rx: &mut mpsc::Receiver<char>) -> Option<(char, char)> {
let a = rx.recv().await?;
println!(" reçu {a}");
let b = rx.recv().await?;
println!(" reçu {b}");
Some((a, b))
}
let mut paires = 0;
loop {
tokio::select! {
p = lire_paire(&mut rx) => match p {
Some(p) => { paires += 1; println!("paire : {p:?}"); }
None => break,
},
_ = sleep(Duration::from_millis(70)) => println!("tic"),
}
}
println!("paires : {paires}");L’émetteur envoie a, attend 100 ms, envoie b et c, attend 100 ms, envoie d, puis ferme le canal.
reçu a
tic
reçu b
reçu c
paire : ('b', 'c')
tic
reçu d
paires : 1Quatre messages envoyés, une seule paire, et ce n’est pas la bonne. Aucune erreur, aucun panic.
temps 0 ms 70 ms 100 ms 170 ms 200 ms
canal a b c d
future 1 [a, ?] ──────╳ tic : détruit, a part avec lui
future 2 [?, ?] ─ [b, c] ▶ paire
future 3 [?, ?] ─╳ tic
future 4 [?, ?] ─ [d, ?] ▶ canal ferméÀ chaque tour de boucle, lire_paire(&mut rx) crée un future neuf. Le premier a retiré a du canal et l’a rangé dans sa variable locale, c’est-à-dire dans le future. Quand le minuteur gagne, select! détruit ce future, et a avec lui. Le suivant repart de zéro.
On dit que lire_paire n’est pas cancel-safe : la détruire à un .await perd quelque chose. rx.recv() seul l’est : tant qu’il n’a pas rendu de message, il n’en a retiré aucun.
La correction : emprunter le future au lieu de le recréer
'dehors: loop {
let lecture = lire_paire(&mut rx);
tokio::pin!(lecture);
loop {
tokio::select! {
p = &mut lecture => match p {
Some(p) => { paires += 1; println!("paire : {p:?}"); break; }
None => break 'dehors,
},
_ = sleep(Duration::from_millis(70)) => println!("tic"),
}
}
} reçu a
tic
reçu b
paire : ('a', 'b')
reçu c
tic
reçu d
paire : ('c', 'd')
paires : 2Le future est créé une fois par paire, hors de la boucle intérieure. select! ne reçoit qu’un emprunt, &mut lecture. Quand le tic gagne, c’est l’emprunt qui est lâché ; le future reste en vie, avec a dedans, et reprend au tour suivant. tokio::pin! l’épingle sur la pile, ce qu’il faut pour pouvoir le poller à travers une référence.
L’autre correction est de conception : garder l’état hors du future. Si a est rangé dans une variable de la boucle et que select! n’attend que rx.recv(), il n’y a plus rien à perdre.
Ce que l’image cache
- L’ordre des branches n’est pas l’ordre de vérification. Quand plusieurs branches sont prêtes en même temps,
select!en choisit une au hasard, pour qu’aucune n’affame les autres.biased;en première ligne impose l’ordre d’écriture. Dropest synchrone. Un future annulé peut fermer un fichier ou relâcher un verrou, mais il ne peut pas.awaitdans son nettoyage : pas de message d’adieu sur le réseau, pas deflushasynchrone.- L’arrêt coopératif existe. Pour qu’une tâche finisse proprement ce qu’elle a commencé, on lui passe un
CancellationToken(cratetokio-util) : elle attendtoken.cancelled()dans son propreselect!et choisit où s’arrêter. - La documentation dit ce qui est cancel-safe. Chaque méthode async de Tokio a une section « Cancel safety ».
recvl’est ;read_exactetwrite_allne le sont pas, parce qu’ils peuvent être détruits après un travail partiel. - Une tâche lancée depuis un future annulé continue. Si le future perdant avait fait un
tokio::spawn, la tâche est détachée, comme avec unJoinHandledétruit. UnJoinSetrétablit le lien : le détruire annule toutes ses tâches. - Un
timeoutn’arrête pas le monde extérieur. Il détruit ton future, pas la requête déjà partie : le serveur en face peut très bien finir le travail. select!n’est pas réservé à Tokio. La cratefuturesa sa propre macro, avec les mêmes conséquences : c’est le modèle des futures qui annule par destruction, pas le runtime.
Pour aller plus loin
- Volume 8, numéro 03 de The Rust Loop, Annuler, sélectionner, structurer, qui part du
.awaitcomme point d’annulation et va jusqu’à la concurrence structurée (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), Future et .await (E0728), les fonctions colorées et Send. - La documentation de
tokio::select!, avec sa section sur la cancellation safety - La documentation de Tokio :
timeout,JoinHandleetJoinSet CancellationToken, danstokio-util
select!: a race
A slow future, which does three 100 ms steps, and a witness that reports its destruction:
struct Temoin(&'static str);
impl Drop for Temoin {
fn drop(&mut self) {
println!(" {} : détruit", self.0);
}
}
async fn lent() -> &'static str {
let _t = Temoin("lent");
for i in 1..=3 {
println!(" lent : étape {i}");
sleep(Duration::from_millis(100)).await;
}
"lent"
}
#[tokio::main]
async fn main() {
let gagnant = tokio::select! {
v = lent() => v,
_ = sleep(Duration::from_millis(150)) => "minuteur",
};
println!("gagnant : {gagnant}");
} lent : étape 1
lent : étape 2
lent : détruit
gagnant : minuteurselect! polls its two futures in the same task, with no extra thread. Each one advances up to its next .await. The first one ready wins; the other is dropped.
0 ms 100 ms 150 ms 200 ms 300 ms
lent() ├─ step 1 ───┼─ step 2 ──╳ ░░░░░░░░░░░░░░░░░░░ dropped at its .await
sleep ├────────────────────────▶ ready: its branch winsThree things to read in that output:
étape 3is never printed.lentwas paused in its secondsleep; nobody will poll it again.lent : détruitis printed. Dropping a future means dropping its local variables, hence_t. Cleanup throughDropalso works for a cancelled future.lentdid nothing to be cancellable. Every future is, at each of its.await.
timeout: the same race, wrapped up
match timeout(Duration::from_millis(150), lent()).await {
Ok(v) => println!("terminé : {v}"),
Err(e) => println!("{e}"),
}
match timeout(Duration::from_millis(500), lent()).await {
Ok(v) => println!("terminé : {v}"),
Err(e) => println!("{e}"),
} lent : étape 1
lent : étape 2
lent : détruit
deadline has elapsed
lent : étape 1
lent : étape 2
lent : étape 3
lent : détruit
terminé : lenttimeout races a future against a timer. If the timer wins, the future is dropped and you get Err(Elapsed), which displays as deadline has elapsed. It isn’t a panic: it’s an ordinary Result, to handle with match or ?. With 500 ms, the future finishes in time, and its witness is dropped normally, at the end of the function.
join! waits for all, select! waits for the first
async fn etape(nom: &'static str, ms: u64) -> &'static str {
sleep(Duration::from_millis(ms)).await;
println!(" {nom} : fini");
nom
}
let (a, b) = tokio::join!(etape("a", 100), etape("b", 200));
// then
let g = tokio::select! {
v = etape("a", 100) => v,
v = etape("b", 200) => v,
}; a : fini
b : fini
join! : a et b, 200 ms environ
a : fini
select! : a seul, 100 ms environBoth macros poll several futures in a single task. join! keeps going until all of them have finished and returns every value. select! stops at the first one, and b : fini isn’t printed: b was dropped midway.
| waits for | returns | the other futures | |
|---|---|---|---|
join! | all | every value | run to completion |
select! | the first one ready | one value | are dropped |
A spawned task no longer belongs to whoever spawned it
So far, dropping the future was enough. With tokio::spawn, the rule changes: the task is handed to the runtime, and the JoinHandle is only a way to follow it.
println!("drop du JoinHandle :");
let h = tokio::spawn(tache("a"));
sleep(Duration::from_millis(150)).await;
drop(h);
println!(" handle détruit");
sleep(Duration::from_millis(250)).await;
println!("abort :");
let h = tokio::spawn(tache("b"));
sleep(Duration::from_millis(150)).await;
h.abort();
match h.await {
Ok(v) => println!(" résultat : {v}"),
Err(e) => println!(" erreur : {e} (is_cancelled : {})", e.is_cancelled()),
}tache is the same three-step future as lent, with a name.
drop du JoinHandle :
a : étape 1
a : étape 2
handle détruit
a : étape 3
a : détruit
abort :
b : étape 1
b : étape 2
b : détruit
erreur : task 12 was cancelled (is_cancelled : true)Dropping the JoinHandle detaches the task: a goes on to step 3, and its result is lost. To cancel it you have to ask, with abort(). Task b is then dropped at its next .await, and awaiting it returns a JoinError (the task number varies from one run to the next).
future awaited directly task started with spawn
┌──────────────┐ ┌──────────────┐ ┌──────────┐
│ select! │ owns │ JoinHandle │ follows │ runtime │ owns
│ timeout ├───▶ future │ ├─ ─ ─ ─ ▶│ ├───▶ task
└──────────────┘ └──────────────┘ └──────────┘
dropping = cancelling dropping = detaching; abort() = cancellingCancellation only happens at an .await
let h = tokio::spawn(async {
println!(" calcul : début");
std::thread::sleep(Duration::from_millis(300));
println!(" calcul : fin");
42
});
sleep(Duration::from_millis(100)).await;
h.abort();
println!("abort demandé");
match h.await {
Ok(v) => println!("résultat : {v}"),
Err(e) => println!("erreur : {e}"),
} calcul : début
abort demandé
calcul : fin
résultat : 42abort is requested at 100 ms, in the middle of the computation. The task finishes anyway and returns 42. It contains no .await: there is no place where it is stopped, hence no place to drop it. It’s the same fact as in the article on colored functions: between two .await, a future doesn’t yield. A timeout around a blocking call doesn’t expire any sooner, for the same reason.
What cancellation takes away
Here is the trap. A function that reads two messages from a channel, and a loop that waits for it while printing a “tic” every 70 ms of silence:
async fn lire_paire(rx: &mut mpsc::Receiver<char>) -> Option<(char, char)> {
let a = rx.recv().await?;
println!(" reçu {a}");
let b = rx.recv().await?;
println!(" reçu {b}");
Some((a, b))
}
let mut paires = 0;
loop {
tokio::select! {
p = lire_paire(&mut rx) => match p {
Some(p) => { paires += 1; println!("paire : {p:?}"); }
None => break,
},
_ = sleep(Duration::from_millis(70)) => println!("tic"),
}
}
println!("paires : {paires}");The sender sends a, waits 100 ms, sends b and c, waits 100 ms, sends d, then closes the channel.
reçu a
tic
reçu b
reçu c
paire : ('b', 'c')
tic
reçu d
paires : 1Four messages sent, a single pair, and not the right one. No error, no panic.
time 0 ms 70 ms 100 ms 170 ms 200 ms
channel a b c d
future 1 [a, ?] ──────╳ tic: dropped, a goes with it
future 2 [?, ?] ─ [b, c] ▶ pair
future 3 [?, ?] ─╳ tic
future 4 [?, ?] ─ [d, ?] ▶ channel closedOn every turn of the loop, lire_paire(&mut rx) creates a fresh future. The first one took a out of the channel and stored it in its local variable, that is, in the future. When the timer wins, select! drops that future, and a with it. The next one starts from scratch.
We say lire_paire isn’t cancel-safe: dropping it at an .await loses something. rx.recv() alone is: as long as it hasn’t returned a message, it hasn’t removed any.
The fix: borrow the future instead of recreating it
'dehors: loop {
let lecture = lire_paire(&mut rx);
tokio::pin!(lecture);
loop {
tokio::select! {
p = &mut lecture => match p {
Some(p) => { paires += 1; println!("paire : {p:?}"); break; }
None => break 'dehors,
},
_ = sleep(Duration::from_millis(70)) => println!("tic"),
}
}
} reçu a
tic
reçu b
paire : ('a', 'b')
reçu c
tic
reçu d
paire : ('c', 'd')
paires : 2The future is created once per pair, outside the inner loop. select! only receives a borrow, &mut lecture. When the tic wins, the borrow is what gets dropped; the future stays alive, with a inside, and resumes on the next turn. tokio::pin! pins it on the stack, which is what it takes to poll it through a reference.
The other fix is a design one: keep the state out of the future. If a is stored in a variable of the loop and select! only awaits rx.recv(), there is nothing left to lose.
What the picture hides
- Branch order isn’t checking order. When several branches are ready at the same time,
select!picks one at random, so that none starves the others.biased;on the first line enforces the written order. Dropis synchronous. A cancelled future can close a file or release a lock, but it cannot.awaitin its cleanup: no goodbye message on the network, no asynchronousflush.- Cooperative shutdown exists. For a task to cleanly finish what it started, you pass it a
CancellationToken(tokio-utilcrate): it awaitstoken.cancelled()in its ownselect!and chooses where to stop. - The documentation says what is cancel-safe. Every async method in Tokio has a “Cancel safety” section.
recvis;read_exactandwrite_allaren’t, because they can be dropped after partial work. - A task spawned from a cancelled future keeps running. If the losing future had done a
tokio::spawn, the task is detached, as with a droppedJoinHandle. AJoinSetrestores the link: dropping it aborts all its tasks. - A
timeoutdoesn’t stop the outside world. It drops your future, not the request already sent: the server on the other end may well finish the work. select!isn’t Tokio-only. Thefuturescrate has its own macro, with the same consequences: it is the futures model that cancels by dropping, not the runtime.
Going further
- Volume 8, issue 03 of The Rust Loop, Cancel, select, structure, which starts from
.awaitas a cancellation point and goes all the way to structured concurrency (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), Future and .await (E0728), colored functions and Send. - The
tokio::select!documentation, with its section on cancellation safety - The Tokio documentation:
timeout,JoinHandleandJoinSet CancellationToken, intokio-util