« future cannot be sent between threads safely » : les fonctions colorées en Rust async "future cannot be sent between threads safely": colored functions in async Rust

En Rust, async est contagieux deux fois. Une fonction synchrone ne peut pas .await (E0728), donc async remonte la chaîne d'appels jusqu'à block_on. Et tout ce qui est vivant pendant un .await est stocké dans le future : un Rc ou un MutexGuard gardé à travers la pause donne « future cannot be sent between threads safely » avec tokio::spawn. Les corrections, le piège de drop, spawn_blocking et le panic « Cannot start a runtime from within a runtime ». Animation et sorties réelles de rustc.In Rust, async is contagious twice. A synchronous function cannot .await (E0728), so async climbs the call chain up to block_on. And everything alive during an .await is stored in the future: an Rc or a MutexGuard kept across the pause gives "future cannot be sent between threads safely" with tokio::spawn. The fixes, the drop pitfall, spawn_blocking and the "Cannot start a runtime from within a runtime" panic. Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
AsyncAsync
PubliéPublished

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’est Send que 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 is Send only 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
}
La couleur d’une fonctionA function’s colour.await n’est permis que dans du code async.await is only allowed in async codela chaîne d’appelsthe call chainmainfnservirfntraiterfnE0728E0728lireasync fnasync remonte vers l’appelantasync climbs towards the callerasyncsynchronesynchronousrefusérefusedsortie du programmeprogram outputne compile pasdoes not compilesorties : rustc 1.100output: rustc 1.100.await met la fonction en pause : seule une fonction async le peut.await pauses the function: only an async function can do thatE0728 : traiter n’est pas async, .await refuséE0728: traiter is not async, .await refused
  1. lire est async : elle attend le réseau. traiter, une fonction ordinaire, veut son résultat et écrit .await. Refusé (E0728) : .await met la fonction en pause, et seule une fonction async sait se mettre en pause. Une fonction a donc une « couleur » : synchrone ou async.lire is async: it waits for the network. traiter, an ordinary function, wants its result and writes .await. Refused (E0728): .await pauses the function, and only an async function knows how to pause. So a function has a "colour": synchronous or async.
  2. La correction évidente : rendre traiter async. Mais alors traiter() rend un future, et son appelant servir a 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: make traiter async. But then traiter() returns a future, and its caller servir needs .await in turn. The same error comes back one level up. The problem isn't solved, it has moved.
  3. La remontée s'arrête là où quelqu'un exécute le future au lieu de l'attendre : un exécuteur. block_on est 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, dans main.The climb stops where someone runs the future instead of awaiting it: an executor. block_on is 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, in main.
  4. Le raccourci tentant : garder traiter synchrone et y appeler block_on. Ça compile. Mais si traiter est 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: keep traiter synchronous and call block_on inside it. It compiles. But if traiter is called from async code, the thread is already busy driving the executor: Tokio refuses at run time, with a panic.
Les fonctions colorées en Rust : .await n’est permis que dans une fonction async (E0728), donc async remonte la chaîne d’appels jusqu’à un exécuteur. block_on est la frontière ; l’appeler depuis une tâche Tokio provoque le panic « Cannot start a runtime from within a runtime ».Colored functions in Rust: .await is only allowed in an async function (E0728), so async climbs the call chain up to an executor. block_on is the boundary; calling it from a Tokio task triggers the "Cannot start a runtime from within a runtime" 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 blocks

traiter 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 blocks

La 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'appelant

C’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 synchroneappelle de l’async
fonction synchroneouiseulement via block_on
fonction asyncoui (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 environ

Le 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 later

Rien dans tache ne parle de threads. L’erreur vient de la rencontre de trois faits :

  1. tokio::spawn confie 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.
  2. compteur est vivant avant et après le .await. Pour que la fonction puisse reprendre, il est rangé dans le future pendant la pause.
  3. Un Rc n’est pas Send (son compteur n’est pas atomique). Un future qui contient un Rc ne 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 spawn

C’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 : 2

Pendant 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 : 1

block_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 later

Arc<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 : 2

Quand 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

  • drop ne suffit presque jamais. drop(compteur); juste avant le .await ne lève l’erreur que si compteur n’a jamais été emprunté. Un seul println!("{compteur}") ou *compteur avant le drop, et l’erreur revient : « await occurs here, with compteur maybe 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.
  • Send n’est pas la seule exigence de spawn. 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 : move et Arc.
  • La couleur a une raison d’être. Une async fn et une fn ne 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 avec std::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 par spawn_blocking.
  • L’erreur n’a pas de code. « future cannot be sent between threads safely » ne porte pas de numéro E0xxx : rustc --explain ne t’aidera pas. Tout est dans la note qui suit, qui nomme la variable et le .await.

Pour aller plus loin

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 blocks

traiter 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 blocks

The 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 caller

This 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 synccalls async
synchronous functionyesonly through block_on
async functionyes (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 environ

The 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 later

Nothing in tache mentions threads. The error comes from three facts meeting:

  1. tokio::spawn hands 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.
  2. compteur is alive before and after the .await. For the function to be able to resume, it is stored in the future during the pause.
  3. An Rc isn’t Send (its counter isn’t atomic). A future that contains an Rc isn’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 spawn

It 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 : 2

During 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 : 1

block_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 later

Arc<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 : 2

When 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

  • drop is almost never enough. drop(compteur); right before the .await only clears the error if compteur was never borrowed. A single println!("{compteur}") or *compteur before the drop, and the error comes back: “await occurs here, with compteur maybe 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.
  • Send isn’t spawn’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: move and Arc.
  • The colour has a reason to exist. An async fn and a fn don’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 with std::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 through spawn_blocking.
  • The error has no code. “future cannot be sent between threads safely” carries no E0xxx number: rustc --explain won’t help you. Everything is in the note that follows, which names the variable and the .await.

Going further

Questions fréquentesFrequently asked questions

Que signifie « future cannot be sent between threads safely » ?What does "future cannot be sent between threads safely" mean?

Tu passes un future à une fonction qui exige Send, le plus souvent tokio::spawn, dont la signature demande F: Future + Send + 'static. Or ton future contient une valeur qui n'est pas Send. La note du compilateur la désigne : « future is not Send as this value is used across an await », avec la variable et le .await concernés. Un future stocke tout ce qui est vivant pendant une pause ; si l'une de ces valeurs est un Rc, un RefCell emprunté ou un MutexGuard de la bibliothèque standard, le future entier n'est plus Send. Correction : faire mourir la valeur avant le .await (dans un bloc), ou la remplacer par un équivalent Send (Arc, tokio::sync::Mutex).You are passing a future to a function that requires Send, most often tokio::spawn, whose signature asks for F: Future + Send + 'static. But your future contains a value that isn't Send. The compiler's note points at it: "future is not Send as this value is used across an await", with the variable and the .await involved. A future stores everything that is alive during a pause; if one of those values is an Rc, a borrowed RefCell or a standard library MutexGuard, the whole future is no longer Send. Fix: make the value die before the .await (in a block), or replace it with a Send equivalent (Arc, tokio::sync::Mutex).

Qu'est-ce que le problème des fonctions colorées ?What is the colored functions problem?

C'est le fait qu'il existe deux sortes de fonctions, synchrones et async, qui ne s'appellent pas librement. Une fonction async peut appeler une fonction synchrone. L'inverse est refusé : .await n'est permis que dans du code async (E0728). Dès qu'une fonction en bas de la pile devient async, son appelant doit le devenir aussi pour attendre son résultat, puis l'appelant de l'appelant, jusqu'à un exécuteur. L'expression vient d'un article de Bob Nystrom de 2015, « What Color is Your Function? ». En Rust, la frontière existe et elle est explicite : block_on.It's the fact that there are two kinds of functions, synchronous and async, that cannot call each other freely. An async function can call a synchronous one. The reverse is refused: .await is only allowed in async code (E0728). As soon as a function at the bottom of the stack becomes async, its caller must become async too in order to await its result, then the caller's caller, up to an executor. The phrase comes from Bob Nystrom's 2015 essay, "What Color is Your Function?". In Rust, the boundary exists and it is explicit: block_on.

Pourquoi drop() avant le .await ne suffit-il pas à rendre mon future Send ?Why isn't drop() before the .await enough to make my future Send?

Il ne suffit que si la variable n'a jamais été empruntée. Avec let compteur = Rc::new(1); drop(compteur); pause().await;, rustc 1.100 compile : le compilateur suit le déplacement, et le future ne garde rien. Mais un seul emprunt avant le drop, même terminé (un println!("{compteur}"), un *compteur), et rustc refuse : « await occurs here, with compteur maybe used later ». Une variable qui a été empruntée est comptée comme vivante jusqu'à la fin de sa portée, même après le déplacement de sa valeur. Comme on crée rarement une valeur sans s'en servir, drop() seul échoue presque toujours en pratique ; c'est vrai aussi d'un MutexGuard après *garde += 1. La correction fiable est un bloc : { let compteur = Rc::new(1); ... } suivi du .await. À l'accolade fermante la variable n'existe plus, et le future ne la contient pas.It is only enough if the variable was never borrowed. With let compteur = Rc::new(1); drop(compteur); pause().await;, rustc 1.100 compiles: the compiler tracks the move, and the future keeps nothing. But a single borrow before the drop, even a finished one (a println!("{compteur}"), a *compteur), and rustc refuses: "await occurs here, with compteur maybe used later". A variable that has been borrowed counts as alive until the end of its scope, even after its value has been moved out. Since you rarely create a value without using it, drop() alone almost always fails in practice; the same goes for a MutexGuard after *garde += 1. The reliable fix is a block: { let compteur = Rc::new(1); ... } followed by the .await. At the closing brace the variable no longer exists, and the future doesn't contain it.

Peut-on garder un MutexGuard à travers un .await ?Can you hold a MutexGuard across an .await?

Pas celui de std::sync::Mutex dans une tâche lancée avec tokio::spawn : MutexGuard n'est pas Send, et le compilateur répond « future cannot be sent between threads safely ». Deux corrections. La plus courante : relâcher le verrou avant le .await, en enfermant le garde dans un bloc, puis le reprendre après si besoin. L'autre : utiliser tokio::sync::Mutex, dont lock() est async et dont le garde est Send, quand il faut vraiment tenir le verrou pendant une attente. La première est préférable par défaut : un verrou tenu pendant une pause bloque toutes les autres tâches qui le veulent.Not the std::sync::Mutex one in a task started with tokio::spawn: MutexGuard isn't Send, and the compiler answers "future cannot be sent between threads safely". Two fixes. The most common: release the lock before the .await, by enclosing the guard in a block, then take it again afterwards if needed. The other: use tokio::sync::Mutex, whose lock() is async and whose guard is Send, when you really have to hold the lock during a wait. The first is the better default: a lock held during a pause blocks every other task that wants it.

Comment appeler du code async depuis une fonction synchrone ?How do you call async code from a synchronous function?

Avec un exécuteur : block_on prend un future et bloque le thread courant jusqu'à son résultat. Avec Tokio : Runtime::new().unwrap().block_on(fut), ou #[tokio::main] qui génère ce code pour main. Mais block_on n'a sa place qu'à la frontière, hors de tout code async. Appelé depuis une tâche déjà pilotée par le runtime, il provoque un panic : « Cannot start a runtime from within a runtime ». Dans l'autre sens, pour du code bloquant ou un calcul long appelé depuis async, utilise tokio::task::spawn_blocking, qui le déporte sur un thread dédié.With an executor: block_on takes a future and blocks the current thread until its result. With Tokio: Runtime::new().unwrap().block_on(fut), or #[tokio::main], which generates that code for main. But block_on only belongs at the boundary, outside any async code. Called from a task already driven by the runtime, it triggers a panic: "Cannot start a runtime from within a runtime". In the other direction, for blocking code or a long computation called from async, use tokio::task::spawn_blocking, which moves it to a dedicated thread.

RustAsyncSendTokioModèle mental

← Tous les articlesAll articles