En bref. async est contagieux, et il l’est deux fois. D’abord dans les signatures : une fonction qui attend un future doit être async, donc son appelant aussi, jusqu’en haut du programme. Ensuite dans les données : ce qu’une fonction garde vivant pendant un .await voyage avec elle, et doit pouvoir changer de thread. La première contagion donne E0728 ; la seconde donne l’erreur la plus déroutante du Rust asynchrone, « future cannot be sent between threads safely ».
Le modèle en une phrase
Une fonction a une couleur, synchrone ou async, et seule une fonction async peut
.await. La couleur remonte donc la chaîne d’appels jusqu’à un exécuteur. Et comme un future range dans sa propre valeur tout ce qui survit à un.await, il n’estSendque si tout ce contenu l’est.
Les deux moitiés découlent du même fait, vu dans l’article sur Future et .await : une async fn est une machine à états qui se met en pause.
In short. async is contagious, and it is contagious twice. First in signatures: a function that awaits a future has to be async, and so does its caller, all the way to the top of the program. Then in data: whatever a function keeps alive during an .await travels with it, and must be able to change threads. The first contagion gives E0728; the second gives the most puzzling error in asynchronous Rust, “future cannot be sent between threads safely”.
The model in one sentence
A function has a colour, synchronous or async, and only an async function can
.await. So the colour climbs the call chain up to an executor. And since a future stores inside its own value everything that survives an.await, it isSendonly if all of that content is.
Both halves follow from the same fact, seen in the article on Future and .await: an async fn is a state machine that pauses.
async fn lire() -> u32 { /* … */ }fn traiter() -> u32 {lire().await + 1}
lireest async : elle attend le réseau.traiter, une fonction ordinaire, veut son résultat et écrit.await. Refusé (E0728) :.awaitmet la fonction en pause, et seule une fonction async sait se mettre en pause. Une fonction a donc une « couleur » : synchrone ou async.lireis async: it waits for the network.traiter, an ordinary function, wants its result and writes.await. Refused (E0728):.awaitpauses the function, and only an async function knows how to pause. So a function has a "colour": synchronous or async.- La correction évidente : rendre
traiterasync. Mais alorstraiter()rend un future, et son appelantservira besoin de.awaità son tour. La même erreur réapparaît un cran plus haut. Le problème n'est pas résolu, il est déplacé.The obvious fix: maketraiterasync. But thentraiter()returns a future, and its callerservirneeds.awaitin turn. The same error comes back one level up. The problem isn't solved, it has moved. - La remontée s'arrête là où quelqu'un exécute le future au lieu de l'attendre : un exécuteur.
block_onest une fonction synchrone qui prend un future et bloque le thread jusqu'à son résultat. C'est la seule porte entre les deux mondes, et on la place tout en haut, dansmain.The climb stops where someone runs the future instead of awaiting it: an executor.block_onis a synchronous function that takes a future and blocks the thread until its result. It's the only door between the two worlds, and it goes at the very top, inmain. - Le raccourci tentant : garder
traitersynchrone et y appelerblock_on. Ça compile. Mais sitraiterest appelée depuis du code async, le thread est déjà occupé à faire tourner l'exécuteur : Tokio refuse à l'exécution, par un panic.The tempting shortcut: keeptraitersynchronous and callblock_oninside it. It compiles. But iftraiteris called from async code, the thread is already busy driving the executor: Tokio refuses at run time, with a panic.
La couleur remonte
Trois fonctions empilées. Tout en bas, lire attend quelque chose (ici un minuteur de Tokio, dans la vraie vie le réseau), donc elle est async.
async fn lire() -> u32 {
tokio::time::sleep(Duration::from_millis(10)).await;
42
}
fn traiter() -> u32 {
lire().await + 1
}error[E0728]: `await` is only allowed inside `async` functions and blocks
--> src/bin/chaine_err.rs:9:12
|
8 | fn traiter() -> u32 {
| ------------------- this is not `async`
9 | lire().await + 1
| ^^^^^ only allowed inside `async` functions and blockstraiter est une fonction ordinaire : elle ne sait pas se mettre en pause, donc elle ne peut pas .await. On la rend async. Son appelant hérite alors du problème :
async fn traiter() -> u32 {
lire().await + 1
}
fn servir() -> String {
format!("réponse : {}", traiter().await)
}error[E0728]: `await` is only allowed inside `async` functions and blocks
--> src/bin/chaine_err2.rs:13:39
|
12 | fn servir() -> String {
| --------------------- this is not `async`
13 | format!("réponse : {}", traiter().await)
| ^^^^^ only allowed inside `async` functions and blocksLa même erreur, un cran plus haut. Rendre une fonction async change son type de retour (elle rend un future, plus une valeur), et ce changement se propage à tous ceux qui veulent le résultat.
main ──▶ servir ──▶ traiter ──▶ lire
fn fn fn async fn E0728 dans traiter
fn fn async fn async fn E0728 dans servir
fn async fn async fn async fn compile, avec block_on dans main
◀───────────────────────┤
async remonte vers l'appelantC’est ce qu’on appelle le problème des fonctions colorées, d’après un article de Bob Nystrom : deux couleurs de fonctions, et une règle d’appel qui n’est pas symétrique.
| appelle du synchrone | appelle de l’async | |
|---|---|---|
| fonction synchrone | oui | seulement via block_on |
| fonction async | oui (attention à ce qui bloque) | oui, avec .await |
Où la remontée s’arrête
Elle s’arrête là où quelqu’un exécute le future au lieu de l’attendre. block_on est une fonction synchrone : elle prend un future, le polle jusqu’au bout en bloquant le thread, et rend sa valeur.
async fn servir() -> String {
format!("réponse : {}", traiter().await)
}
fn main() {
let rt = tokio::runtime::Runtime::new().unwrap();
println!("{}", rt.block_on(servir()));
}réponse : 43#[tokio::main] écrit ces deux lignes à ta place. Dans les deux cas, main reste une fonction synchrone : c’est elle qui porte la frontière.
Le raccourci qui panique. Puisque block_on transforme un future en valeur, pourquoi ne pas l’appeler plus bas, dans traiter, et laisser le reste de la chaîne tranquille ?
fn traiter() -> u32 {
Handle::current().block_on(lire()) + 1
}
async fn servir() -> String {
format!("réponse : {}", traiter())
}
#[tokio::main]
async fn main() {
println!("{}", servir().await);
}Ça compile. À l’exécution :
thread 'main' (66083) panicked at src/bin/imbrique.rs:10:23:
Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks. If you are in an async function, use `.await` on the future instead of blocking on it.traiter est appelée depuis servir, donc depuis un thread qui fait tourner l’exécuteur. Bloquer ce thread pour attendre un future que ce même thread doit faire avancer n’a pas d’issue ; Tokio préfère paniquer. block_on est une porte d’entrée dans le monde async, pas un moyen d’en sortir en cours de route.
Async qui appelle du synchrone : permis, mais attention
Dans ce sens, le compilateur ne dit rien. Le risque est ailleurs : entre deux .await, un future ne rend pas la main. Un appel qui bloque le thread bloque l’exécuteur avec lui.
async fn battement(debut: Instant) {
for _ in 0..3 {
tokio::time::sleep(Duration::from_millis(100)).await;
println!(" battement à {} ms environ", debut.elapsed().as_millis() / 100 * 100);
}
}
async fn calcul_bloquant() {
std::thread::sleep(Duration::from_millis(500));
println!(" calcul terminé");
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
let debut = Instant::now();
tokio::join!(battement(debut), calcul_bloquant());
} calcul terminé
battement à 500 ms environ
battement à 600 ms environ
battement à 700 ms environLe premier battement devait arriver à 100 ms. Il arrive à 500 : pendant le thread::sleep, l’unique thread de l’exécuteur ne pouvait rien faire d’autre. La correction est de déporter le travail bloquant sur un thread prévu pour ça :
async fn calcul_bloquant() {
tokio::task::spawn_blocking(|| {
std::thread::sleep(Duration::from_millis(500));
})
.await
.unwrap();
println!(" calcul terminé");
} battement à 100 ms environ
battement à 200 ms environ
battement à 300 ms environ
calcul terminéspawn_blocking rend un future : le code bloquant redevient quelque chose qu’on peut .await.
Send à travers .await
Seconde contagion. Elle ne touche plus les signatures, mais les données.
async fn pause() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
async fn tache() {
let compteur = Rc::new(1);
pause().await;
println!("compteur : {compteur}");
}
#[tokio::main]
async fn main() {
tokio::spawn(tache()).await.unwrap();
}error: future cannot be sent between threads safely
--> src/bin/rc.rs:16:18
|
16 | tokio::spawn(tache()).await.unwrap();
| ^^^^^^^ future returned by `tache` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `Rc<i32>`
note: future is not `Send` as this value is used across an await
--> src/bin/rc.rs:10:13
|
9 | let compteur = Rc::new(1);
| -------- has type `Rc<i32>` which is not `Send`
10 | pause().await;
| ^^^^^ await occurs here, with `compteur` maybe used laterRien dans tache ne parle de threads. L’erreur vient de la rencontre de trois faits :
tokio::spawnconfie la tâche à un groupe de threads. Après une pause, n’importe lequel peut la reprendre. Sa signature l’exige donc :F: Future + Send + 'static.compteurest vivant avant et après le.await. Pour que la fonction puisse reprendre, il est rangé dans le future pendant la pause.- Un
Rcn’est pasSend(son compteur n’est pas atomique). Un future qui contient unRcne l’est pas non plus.
pause().await
thread 1 ─────────────────┤
let compteur = Rc::new(1)
│ le future est rangé, avec son contenu :
│ ┌───────────────────────┐
│ │ où reprendre │
│ │ compteur : Rc<i32> │ ◀── pas Send
│ └───────────────────────┘
thread 2 ├──────────────────────────────▶
println!("{compteur}") refusé par spawnC’est la règle de Send et Sync, appliquée à une structure que tu n’as pas écrite : la machine à états générée par le compilateur.
Trois corrections
Faire mourir la valeur avant la pause. Un bloc qui se termine avant le .await :
async fn tache() {
let n = {
let compteur = Rc::new(1);
*compteur + 1
};
pause().await;
println!("n : {n}");
}n : 2Pendant la pause, le future ne garde plus qu’un i32. On peut le vérifier sans spawn, avec une fonction qui n’accepte que du Send :
fn est_send<T: Send>(_: &T) {}
let f = tache();
est_send(&f);Ce code compile avec la version à bloc, et échoue avec la première.
Prendre un type qui est Send. Arc à la place de Rc : la fonction d’origine compile sans autre changement et affiche compteur : 1.
Ne pas demander Send. La contrainte vient de spawn, pas d’async. Le même future non-Send, attendu directement, fonctionne :
#[tokio::main]
async fn main() {
tache().await;
}compteur : 1block_on fait tourner son future sur le thread qui l’appelle : il n’y a pas de migration, donc pas d’exigence. Pour lancer plusieurs tâches non-Send, Tokio fournit LocalSet et spawn_local, qui les gardent toutes sur un même thread.
Le cas qu’on rencontre vraiment : le verrou
async fn tache(total: Arc<Mutex<u32>>) {
let mut garde = total.lock().unwrap();
*garde += 1;
pause().await;
*garde += 1;
}error: future cannot be sent between threads safely
--> src/bin/garde.rs:18:18
|
18 | tokio::spawn(tache(total.clone())).await.unwrap();
| ^^^^^^^^^^^^^^^^^^^^ future returned by `tache` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, u32>`
note: future is not `Send` as this value is used across an await
--> src/bin/garde.rs:11:13
|
9 | let mut garde = total.lock().unwrap();
| --------- has type `std::sync::MutexGuard<'_, u32>` which is not `Send`
10 | *garde += 1;
11 | pause().await;
| ^^^^^ await occurs here, with `mut garde` maybe used laterArc<Mutex<u32>> est Send, mais le garde rendu par lock() ne l’est pas : un verrou doit être relâché par le thread qui l’a pris. Ici l’erreur de compilation signale un vrai défaut de conception. Tenir un verrou pendant une pause, c’est le tenir pendant un temps qu’on ne maîtrise pas, et faire attendre toutes les tâches qui le veulent.
La correction habituelle : relâcher avant, reprendre après.
async fn tache(total: Arc<Mutex<u32>>) {
{
let mut garde = total.lock().unwrap();
*garde += 1;
}
pause().await;
*total.lock().unwrap() += 1;
}total : 2Quand il faut vraiment tenir le verrou pendant l’attente, tokio::sync::Mutex existe pour ça : son lock() est async (total.lock().await) et son garde est Send. Le programme d’origine, avec ce seul changement de type, compile et affiche aussi total : 2.
Ce que l’image cache
dropne suffit presque jamais.drop(compteur);juste avant le.awaitne lève l’erreur que sicompteurn’a jamais été emprunté. Un seulprintln!("{compteur}")ou*compteuravant ledrop, et l’erreur revient : « await occurs here, withcompteurmaybe used later ». Une variable empruntée reste comptée comme vivante jusqu’à la fin de sa portée, même une fois sa valeur déplacée. Le bloc, lui, marche dans tous les cas.- Un temporaire compte aussi. Le garde n’a pas besoin d’un nom : dans
f(*total.lock().unwrap()).await, le garde temporaire vit jusqu’à la fin de l’instruction, donc à travers le.await. Sendn’est pas la seule exigence despawn. Il demande aussi'static: la tâche peut survivre à la fonction qui l’a lancée, donc elle ne peut pas emprunter ses variables locales. C’est la même contrainte que pour les threads, avec la même réponse :moveetArc.- La couleur a une raison d’être. Une
async fnet unefnne rendent pas le même type. La « couleur » est cette différence de type rendue visible, et c’est elle qui indique, à la lecture, où le code peut être mis en pause. - Les traits aussi sont colorés. Une méthode de trait est synchrone ou async, pas les deux. Une bibliothèque qui veut servir les deux mondes expose souvent deux API.
- Bloquer n’est pas que
thread::sleep. Une lecture de fichier avecstd::fs, une requête avec un client synchrone, un calcul de plusieurs millisecondes : tout ce qui ne rend pas la main compte. La règle pratique est de passer par les équivalents async, ou parspawn_blocking. - L’erreur n’a pas de code. « future cannot be sent between threads safely » ne porte pas de numéro
E0xxx:rustc --explainne t’aidera pas. Tout est dans la note qui suit, qui nomme la variable et le.await.
Pour aller plus loin
- Volume 8, numéro 02 de The Rust Loop, Le problème des fonctions colorées, qui suit la contagion d’async dans les signatures et le retour de
Sendau milieu du code asynchrone (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). - The Rust Book : les fondamentaux de la programmation asynchrone
- La documentation de Tokio :
spawn,spawn_blocking,tokio::sync::MutexetLocalSet - Bob Nystrom, « What Color is Your Function? », l’article qui a donné son nom au problème
The colour climbs
Three stacked functions. At the bottom, lire waits for something (here a Tokio timer, in real life the network), so it is async.
async fn lire() -> u32 {
tokio::time::sleep(Duration::from_millis(10)).await;
42
}
fn traiter() -> u32 {
lire().await + 1
}error[E0728]: `await` is only allowed inside `async` functions and blocks
--> src/bin/chaine_err.rs:9:12
|
8 | fn traiter() -> u32 {
| ------------------- this is not `async`
9 | lire().await + 1
| ^^^^^ only allowed inside `async` functions and blockstraiter is an ordinary function: it doesn’t know how to pause, so it cannot .await. We make it async. Its caller then inherits the problem:
async fn traiter() -> u32 {
lire().await + 1
}
fn servir() -> String {
format!("réponse : {}", traiter().await)
}error[E0728]: `await` is only allowed inside `async` functions and blocks
--> src/bin/chaine_err2.rs:13:39
|
12 | fn servir() -> String {
| --------------------- this is not `async`
13 | format!("réponse : {}", traiter().await)
| ^^^^^ only allowed inside `async` functions and blocksThe same error, one level up. Making a function async changes its return type (it returns a future, no longer a value), and that change propagates to everyone who wants the result.
main ──▶ servir ──▶ traiter ──▶ lire
fn fn fn async fn E0728 in traiter
fn fn async fn async fn E0728 in servir
fn async fn async fn async fn compiles, with block_on in main
◀───────────────────────┤
async climbs towards the callerThis is what is called the colored functions problem, after an essay by Bob Nystrom: two colours of functions, and a calling rule that isn’t symmetric.
| calls sync | calls async | |
|---|---|---|
| synchronous function | yes | only through block_on |
| async function | yes (mind what blocks) | yes, with .await |
Where the climb stops
It stops where someone runs the future instead of awaiting it. block_on is a synchronous function: it takes a future, polls it to completion while blocking the thread, and returns its value.
async fn servir() -> String {
format!("réponse : {}", traiter().await)
}
fn main() {
let rt = tokio::runtime::Runtime::new().unwrap();
println!("{}", rt.block_on(servir()));
}réponse : 43#[tokio::main] writes those two lines for you. Either way, main stays a synchronous function: it is the one that carries the boundary.
The shortcut that panics. Since block_on turns a future into a value, why not call it lower down, in traiter, and leave the rest of the chain alone?
fn traiter() -> u32 {
Handle::current().block_on(lire()) + 1
}
async fn servir() -> String {
format!("réponse : {}", traiter())
}
#[tokio::main]
async fn main() {
println!("{}", servir().await);
}It compiles. At run time:
thread 'main' (66083) panicked at src/bin/imbrique.rs:10:23:
Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks. If you are in an async function, use `.await` on the future instead of blocking on it.traiter is called from servir, hence from a thread that is driving the executor. Blocking that thread to wait for a future that the very same thread has to advance leads nowhere; Tokio prefers to panic. block_on is a way into the async world, not a way out of it midway.
Async calling sync: allowed, but careful
In this direction, the compiler says nothing. The risk lies elsewhere: between two .await, a future doesn’t yield. A call that blocks the thread blocks the executor with it.
async fn battement(debut: Instant) {
for _ in 0..3 {
tokio::time::sleep(Duration::from_millis(100)).await;
println!(" battement à {} ms environ", debut.elapsed().as_millis() / 100 * 100);
}
}
async fn calcul_bloquant() {
std::thread::sleep(Duration::from_millis(500));
println!(" calcul terminé");
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
let debut = Instant::now();
tokio::join!(battement(debut), calcul_bloquant());
} calcul terminé
battement à 500 ms environ
battement à 600 ms environ
battement à 700 ms environThe first beat was due at 100 ms. It arrives at 500: during the thread::sleep, the executor’s only thread could do nothing else. The fix is to move the blocking work to a thread meant for it:
async fn calcul_bloquant() {
tokio::task::spawn_blocking(|| {
std::thread::sleep(Duration::from_millis(500));
})
.await
.unwrap();
println!(" calcul terminé");
} battement à 100 ms environ
battement à 200 ms environ
battement à 300 ms environ
calcul terminéspawn_blocking returns a future: the blocking code becomes something you can .await again.
Send across .await
The second contagion. It no longer affects signatures, but data.
async fn pause() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
async fn tache() {
let compteur = Rc::new(1);
pause().await;
println!("compteur : {compteur}");
}
#[tokio::main]
async fn main() {
tokio::spawn(tache()).await.unwrap();
}error: future cannot be sent between threads safely
--> src/bin/rc.rs:16:18
|
16 | tokio::spawn(tache()).await.unwrap();
| ^^^^^^^ future returned by `tache` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `Rc<i32>`
note: future is not `Send` as this value is used across an await
--> src/bin/rc.rs:10:13
|
9 | let compteur = Rc::new(1);
| -------- has type `Rc<i32>` which is not `Send`
10 | pause().await;
| ^^^^^ await occurs here, with `compteur` maybe used laterNothing in tache mentions threads. The error comes from three facts meeting:
tokio::spawnhands the task to a pool of threads. After a pause, any of them may resume it. So its signature requires it:F: Future + Send + 'static.compteuris alive before and after the.await. For the function to be able to resume, it is stored in the future during the pause.- An
Rcisn’tSend(its counter isn’t atomic). A future that contains anRcisn’t either.
pause().await
thread 1 ─────────────────┤
let compteur = Rc::new(1)
│ the future is put away, with its content:
│ ┌───────────────────────┐
│ │ where to resume │
│ │ compteur : Rc<i32> │ ◀── not Send
│ └───────────────────────┘
thread 2 ├──────────────────────────────▶
println!("{compteur}") refused by spawnIt is the rule of Send and Sync, applied to a struct you didn’t write: the state machine generated by the compiler.
Three fixes
Make the value die before the pause. A block that ends before the .await:
async fn tache() {
let n = {
let compteur = Rc::new(1);
*compteur + 1
};
pause().await;
println!("n : {n}");
}n : 2During the pause, the future only keeps an i32. You can check it without spawn, with a function that only accepts Send:
fn est_send<T: Send>(_: &T) {}
let f = tache();
est_send(&f);This code compiles with the block version, and fails with the first one.
Pick a type that is Send. Arc instead of Rc: the original function compiles with no other change and prints compteur : 1.
Don’t ask for Send. The constraint comes from spawn, not from async. The same non-Send future, awaited directly, works:
#[tokio::main]
async fn main() {
tache().await;
}compteur : 1block_on drives its future on the thread that calls it: there is no migration, hence no requirement. To start several non-Send tasks, Tokio provides LocalSet and spawn_local, which keep them all on one thread.
The case you actually run into: the lock
async fn tache(total: Arc<Mutex<u32>>) {
let mut garde = total.lock().unwrap();
*garde += 1;
pause().await;
*garde += 1;
}error: future cannot be sent between threads safely
--> src/bin/garde.rs:18:18
|
18 | tokio::spawn(tache(total.clone())).await.unwrap();
| ^^^^^^^^^^^^^^^^^^^^ future returned by `tache` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, u32>`
note: future is not `Send` as this value is used across an await
--> src/bin/garde.rs:11:13
|
9 | let mut garde = total.lock().unwrap();
| --------- has type `std::sync::MutexGuard<'_, u32>` which is not `Send`
10 | *garde += 1;
11 | pause().await;
| ^^^^^ await occurs here, with `mut garde` maybe used laterArc<Mutex<u32>> is Send, but the guard returned by lock() isn’t: a lock must be released by the thread that took it. Here the compile error points at a real design flaw. Holding a lock during a pause means holding it for a duration you don’t control, and making every task that wants it wait.
The usual fix: release before, take again after.
async fn tache(total: Arc<Mutex<u32>>) {
{
let mut garde = total.lock().unwrap();
*garde += 1;
}
pause().await;
*total.lock().unwrap() += 1;
}total : 2When you really have to hold the lock during the wait, tokio::sync::Mutex exists for that: its lock() is async (total.lock().await) and its guard is Send. The original program, with that single type change, compiles and also prints total : 2.
What the picture hides
dropis almost never enough.drop(compteur);right before the.awaitonly clears the error ifcompteurwas never borrowed. A singleprintln!("{compteur}")or*compteurbefore thedrop, and the error comes back: “await occurs here, withcompteurmaybe used later”. A borrowed variable keeps counting as alive until the end of its scope, even once its value has been moved out. A block works in every case.- A temporary counts too. The guard doesn’t need a name: in
f(*total.lock().unwrap()).await, the temporary guard lives until the end of the statement, hence across the.await. Sendisn’tspawn’s only requirement. It also asks for'static: the task may outlive the function that started it, so it cannot borrow its local variables. It’s the same constraint as for threads, with the same answer:moveandArc.- The colour has a reason to exist. An
async fnand afndon’t return the same type. The “colour” is that type difference made visible, and it is what tells you, when reading, where the code can be paused. - Traits are coloured too. A trait method is synchronous or async, not both. A library that wants to serve both worlds often exposes two APIs.
- Blocking isn’t only
thread::sleep. Reading a file withstd::fs, a request with a synchronous client, a computation of several milliseconds: anything that doesn’t yield counts. The practical rule is to go through the async equivalents, or throughspawn_blocking. - The error has no code. “future cannot be sent between threads safely” carries no
E0xxxnumber:rustc --explainwon’t help you. Everything is in the note that follows, which names the variable and the.await.
Going further
- Volume 8, issue 02 of The Rust Loop, The colored functions problem, which follows the contagion of async through signatures and the return of
Sendin the middle of asynchronous code (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). - The Rust Book: fundamentals of asynchronous programming
- The Tokio documentation:
spawn,spawn_blocking,tokio::sync::MutexandLocalSet - Bob Nystrom, “What Color is Your Function?”, the essay that gave the problem its name