En bref. L’article précédent partageait une donnée entre threads et la protégeait par un verrou. Un canal fait l’inverse : il ne partage rien. Un thread envoie une valeur, un autre la reçoit, et entre les deux elle change de propriétaire. Ce modèle explique à la fois l’erreur de compilation qu’on rencontre en premier (E0382 après un send) et les deux erreurs d’exécution des canaux : sending on a closed channel et receiving on a closed channel.
Le modèle en une phrase
Un canal est une file à deux bouts :
senddéplace la valeur dedans,recvl’en sort. Elle n’a jamais qu’un propriétaire, donc il n’y a rien à verrouiller. Et le canal se ferme tout seul quand l’un des deux bouts disparaît.
C’est le move du premier article, étendu à deux threads. La devise vient de Go : ne communiquez pas en partageant de la mémoire, partagez de la mémoire en communiquant.
In short. The previous article shared data between threads and protected it with a lock. A channel does the opposite: it shares nothing. One thread sends a value, another receives it, and in between it changes owners. This model explains both the compile error you meet first (E0382 after a send) and the two run-time errors of channels: sending on a closed channel and receiving on a closed channel.
The model in one sentence
A channel is a queue with two ends:
sendmoves the value in,recvtakes it out. It only ever has one owner, so there is nothing to lock. And the channel closes by itself when one of the two ends goes away.
It’s the move from the first article, extended to two threads. The motto comes from Go: do not communicate by sharing memory, share memory by communicating.
let (tx, rx) = mpsc::channel();let v = vec![1, 2, 3];
mpsc::channel()rend les deux bouts d'une file : l'émetteurtxet le récepteurrx. On donnetxà un thread avecmove,maingarderx. Les deux threads n'ont aucune donnée en commun.mpsc::channel()returns the two ends of a queue: the sendertxand the receiverrx. You givetxto a thread withmove,mainkeepsrx. The two threads have no data in common.tx.send(v)déplacevdans le canal. Rien n'est copié : seuls le pointeur, la longueur et la capacité duVecvoyagent, le tampon reste où il est. Le thread émetteur n'a plusv.tx.send(v)movesvinto the channel. Nothing is copied: only theVec's pointer, length and capacity travel, the buffer stays where it is. The sending thread no longer hasv.- Relire
vaprès l'envoi est donc refusé : E0382, l'erreur du tout premier article. C'est ce refus qui rend le canal sûr : l'émetteur ne peut pas modifier un message que le récepteur est en train de lire.Readingvagain after sending is therefore refused: E0382, the error from the very first article. That refusal is what makes the channel safe: the sender cannot modify a message the receiver is reading. rx.recv()attend un message et le sort de la file :mainen devient propriétaire. Vérifié : leVecreçu pointe vers le même tampon que celui envoyé. La donnée a changé de thread sans verrou et sans copie.rx.recv()waits for a message and takes it out of the queue:mainbecomes its owner. Checked: the receivedVecpoints to the same buffer as the one sent. The data changed threads with no lock and no copy.
Envoyer, c’est déplacer
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let v = vec![1, 2, 3];
tx.send(v).unwrap();
});
let recu = rx.recv().unwrap();
println!("reçu : {recu:?}");
}reçu : [1, 2, 3]mpsc::channel() rend les deux bouts : tx, l’émetteur (transmitter), et rx, le récepteur. La closure move emporte tx dans le thread, main garde rx. recv() bloque jusqu’à ce qu’un message arrive.
thread canal main
┌────────────┐ ┌─────────────┐ ┌────────────┐
│ v │ ─send──▶ │ [1, 2, 3] │ ─recv──▶ │ recu │
└────────────┘ └─────────────┘ └────────────┘
propriétaire propriétaire propriétaire
avant send pendant le trajet après recvÀ aucun moment deux threads n’ont accès à la valeur. Et le trajet ne copie pas les données. On peut le vérifier en comparant l’adresse du tampon avant l’envoi et après la réception :
let h = thread::spawn(move || {
let v = vec![1, 2, 3];
let avant = v.as_ptr() as usize;
tx.send(v).unwrap();
avant
});
let recu = rx.recv().unwrap();
let avant = h.join().unwrap();
println!("même tampon : {}", avant == recu.as_ptr() as usize);même tampon : trueSeuls le pointeur, la longueur et la capacité du Vec ont voyagé. Le tampon n’a pas bougé : il a changé de propriétaire.
L’erreur : relire après l’envoi
thread::spawn(move || {
let v = vec![1, 2, 3];
tx.send(v).unwrap();
println!("envoyé : {v:?}");
});error[E0382]: borrow of moved value: `v`
--> apres_send.rs:9:29
|
7 | let v = vec![1, 2, 3];
| - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
8 | tx.send(v).unwrap();
| - value moved here
9 | println!("envoyé : {v:?}");
| ^ value borrowed here after moveCe refus n’est pas une gêne, c’est la garantie. Si l’émetteur pouvait encore toucher à v, il pourrait le modifier pendant que le récepteur le lit : une course aux données. Dans d’autres langages, « ne touche plus à ce que tu as envoyé » est une convention. Ici, c’est le système de types qui la tient, sans une ligne de code propre aux canaux : send prend son argument par valeur, et c’est tout.
Si l’émetteur a encore besoin de la donnée, il envoie un clone (tx.send(v.clone())), ou il affiche avant d’envoyer.
Plusieurs producteurs, un consommateur
mpsc signifie multiple producer, single consumer. L’émetteur se clone, et tous les clones alimentent la même file :
let (tx, rx) = mpsc::channel();
for id in 1..=3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(id * 10).unwrap();
});
}
drop(tx);
let mut recus: Vec<i32> = rx.iter().collect();
recus.sort();
println!("reçus : {recus:?}");reçus : [10, 20, 30]Le sort() est là parce que l’ordre d’arrivée entre threads différents n’est pas garanti. Pour un même émetteur, il l’est : un thread qui envoie 1, 2, 3, 4, 5 est reçu [1, 2, 3, 4, 5].
Le compteur de l’article précédent se réécrit sans Arc ni Mutex. Quatre threads envoient mille fois 1, et le récepteur additionne :
let total: i32 = rx.iter().sum();
println!("total : {total}");total : 4000Le total n’appartient qu’au récepteur. Personne d’autre ne peut y écrire, donc il n’y a rien à protéger.
La fermeture : quand la boucle s’arrête
rx.iter() et for n in rx attendent des messages jusqu’à la fermeture du canal. Et le canal se ferme quand tous les émetteurs ont été détruits : c’est le rôle du drop(tx) de l’exemple précédent.
tx (main) ├──────────┤ drop(tx)
tx 1 ├──── send(10) ──┤ fin du thread
tx 2 ├────── send(20) ──┤
tx 3 ├──────── send(30) ──┤
▲
└─ dernier émetteur détruit : canal fermé
rx ├── 10 ── 20 ── 30 ──┤ la boucle se termineRetirons ce drop. Pour ne pas bloquer indéfiniment, cette version mesure avec recv_timeout :
// pas de drop(tx) : main garde un émetteur
let mut n = 0;
loop {
match rx.recv_timeout(Duration::from_millis(500)) {
Ok(_) => n += 1,
Err(e) => {
println!("{n} messages reçus, puis : {e:?}");
break;
}
}
}3 messages reçus, puis : TimeoutTimeout, pas une fermeture. Les trois clones ont disparu, mais main tient toujours l’original : tant qu’un émetteur existe, un message peut encore arriver. Avec un simple for n in rx, le programme attendrait pour toujours un message que lui seul pourrait envoyer. C’est le bug le plus courant avec les canaux, et il compile sans avertissement.
Les deux erreurs de fermeture
Chaque bout apprend la disparition de l’autre par un Result.
Le récepteur a disparu.
let (tx, rx) = mpsc::channel();
drop(rx);
match tx.send(String::from("bonjour")) {
Ok(()) => println!("envoyé"),
Err(e) => println!("erreur : {e} · message rendu : {:?}", e.0),
}erreur : sending on a closed channel · message rendu : "bonjour"Le message n’est pas perdu : SendError le contient, et e.0 le rend. Avec .unwrap() à la place du match, c’est un panic :
thread 'main' (31640) panicked at unwrap_send.rs:6:16:
called `Result::unwrap()` on an `Err` value: SendError { .. }Tous les émetteurs ont disparu.
let (tx, rx) = mpsc::channel();
tx.send(1).unwrap();
drop(tx);
println!("{:?}", rx.recv());
match rx.recv() {
Ok(n) => println!("reçu : {n}"),
Err(e) => println!("erreur : {e}"),
}Ok(1)
erreur : receiving on a closed channelRemarque l’ordre : le message envoyé avant la fermeture est quand même livré. recv ne rend Err qu’une fois la file vide et le canal fermé. C’est exactement ce signal qui termine la boucle for.
sync_channel : un canal borné
mpsc::channel() n’a pas de limite : send ne bloque jamais, et un producteur plus rapide que le consommateur remplit la mémoire. mpsc::sync_channel(n) borne la file à n messages. Quand elle est pleine, send attend :
let (tx, rx) = mpsc::sync_channel(1);
let debut = Instant::now();
let h = thread::spawn(move || {
for i in 1..=3 {
tx.send(i).unwrap();
println!("envoyé {i} après {} ms environ", debut.elapsed().as_millis() / 100 * 100);
}
});
thread::sleep(Duration::from_millis(100));
for n in rx {
println!(" reçu {n}");
thread::sleep(Duration::from_millis(100));
}
h.join().unwrap();envoyé 1 après 0 ms environ
reçu 1
envoyé 2 après 100 ms environ
reçu 2
envoyé 3 après 200 ms environ
reçu 3Le premier envoi passe tout de suite : la file a une place. Le deuxième attend que le récepteur ait pris le premier. Le producteur avance au rythme du consommateur : c’est la contre-pression (backpressure).
Les variantes non bloquantes disent pourquoi elles échouent :
let (tx, rx) = mpsc::sync_channel(1);
println!("{:?}", tx.try_send(1));
println!("{:?}", tx.try_send(2));
println!("{:?}", rx.try_recv());
println!("{:?}", rx.try_recv());
drop(tx);
println!("{:?}", rx.try_recv());Ok(())
Err(TrySendError::Full(..))
Ok(1)
Err(Empty)
Err(Disconnected)Empty : rien pour l’instant, réessaie. Disconnected : plus rien ne viendra jamais.
Ce que l’image cache
- Le récepteur ne se clone pas.
rx.clone()donne E0599, « no method namedclonefound for structstd::sync::mpsc::Receiver<T>». C’est le single consumer dempsc. - Il ne se partage pas non plus. Deux threads scopés qui empruntent le même
rxdonnent E0277, «Receiver<i32>cannot be shared between threads safely » :ReceiverestSendmais pasSync, comme on l’a vu dans le tableau de l’article précédent. - Plusieurs workers :
Arc<Mutex<Receiver<T>>>. Chaque worker prend le verrou, reçoit un message, rend le verrou. Vérifié : deux workers qui se partagent les entiers de 1 à 100 totalisent5050. - Le message doit être
Send. Envoyer unRcdepuis un thread est refusé : E0277, «Rc<i32>cannot be sent between threads safely », avec la note « required forSender<Rc<i32>>to implementSend». - Un canal ne supprime pas tous les blocages. Il n’y a plus de verrou sur la donnée, mais deux threads qui attendent chacun un message de l’autre attendent pour toujours. Le
txoublié en est la version à un seul thread. sendréussi ne veut pas dire « reçu ».Ok(())signifie que le message est dans la file. Si le récepteur disparaît ensuite, le message est détruit avec le canal.- Ce sont les canaux de la bibliothèque standard, bloquants. Le code asynchrone utilise d’autres canaux, construits sur le même modèle de possession.
asyncest le sujet du prochain volume.
Pour aller plus loin
- Volume 7, numéro 03 de The Rust Loop, Les canaux, ou share memory by communicating, qui détaille le passage de messages et la possession transférée par le canal (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). - The Rust Book : transférer des données entre threads par passage de messages
- La bibliothèque standard : le module
mpsc,sync_channeletSendError
Sending is moving
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let v = vec![1, 2, 3];
tx.send(v).unwrap();
});
let recu = rx.recv().unwrap();
println!("reçu : {recu:?}");
}reçu : [1, 2, 3]mpsc::channel() returns the two ends: tx, the transmitter, and rx, the receiver. The move closure takes tx into the thread, main keeps rx. recv() blocks until a message arrives.
thread channel main
┌────────────┐ ┌─────────────┐ ┌────────────┐
│ v │ ─send──▶ │ [1, 2, 3] │ ─recv──▶ │ recu │
└────────────┘ └─────────────┘ └────────────┘
owner owner owner
before send during the trip after recvAt no point do two threads have access to the value. And the trip doesn’t copy the data. You can check it by comparing the buffer’s address before sending and after receiving:
let h = thread::spawn(move || {
let v = vec![1, 2, 3];
let avant = v.as_ptr() as usize;
tx.send(v).unwrap();
avant
});
let recu = rx.recv().unwrap();
let avant = h.join().unwrap();
println!("même tampon : {}", avant == recu.as_ptr() as usize);même tampon : trueOnly the Vec’s pointer, length and capacity travelled. The buffer didn’t move: it changed owners.
The error: reading after sending
thread::spawn(move || {
let v = vec![1, 2, 3];
tx.send(v).unwrap();
println!("envoyé : {v:?}");
});error[E0382]: borrow of moved value: `v`
--> apres_send.rs:9:29
|
7 | let v = vec![1, 2, 3];
| - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
8 | tx.send(v).unwrap();
| - value moved here
9 | println!("envoyé : {v:?}");
| ^ value borrowed here after moveThis refusal isn’t a nuisance, it’s the guarantee. If the sender could still touch v, it could modify it while the receiver reads it: a data race. In other languages, “don’t touch what you’ve sent” is a convention. Here the type system enforces it, without a single line of channel-specific code: send takes its argument by value, and that’s all.
If the sender still needs the data, it sends a clone (tx.send(v.clone())), or prints before sending.
Several producers, one consumer
mpsc stands for multiple producer, single consumer. The sender can be cloned, and all clones feed the same queue:
let (tx, rx) = mpsc::channel();
for id in 1..=3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(id * 10).unwrap();
});
}
drop(tx);
let mut recus: Vec<i32> = rx.iter().collect();
recus.sort();
println!("reçus : {recus:?}");reçus : [10, 20, 30]The sort() is there because arrival order across different threads isn’t guaranteed. For a single sender, it is: a thread sending 1, 2, 3, 4, 5 is received as [1, 2, 3, 4, 5].
The counter from the previous article can be rewritten with no Arc and no Mutex. Four threads send 1 a thousand times, and the receiver adds up:
let total: i32 = rx.iter().sum();
println!("total : {total}");total : 4000The total belongs to the receiver alone. Nobody else can write to it, so there is nothing to protect.
Closing: when the loop stops
rx.iter() and for n in rx wait for messages until the channel closes. And the channel closes when all senders have been dropped: that’s the job of the drop(tx) in the previous example.
tx (main) ├──────────┤ drop(tx)
tx 1 ├──── send(10) ──┤ thread ends
tx 2 ├────── send(20) ──┤
tx 3 ├──────── send(30) ──┤
▲
└─ last sender dropped: channel closed
rx ├── 10 ── 20 ── 30 ──┤ the loop endsLet’s remove that drop. So as not to block forever, this version measures with recv_timeout:
// pas de drop(tx) : main garde un émetteur
let mut n = 0;
loop {
match rx.recv_timeout(Duration::from_millis(500)) {
Ok(_) => n += 1,
Err(e) => {
println!("{n} messages reçus, puis : {e:?}");
break;
}
}
}3 messages reçus, puis : TimeoutTimeout, not a close. The three clones are gone, but main still holds the original: as long as a sender exists, a message may still arrive. With a plain for n in rx, the program would wait forever for a message only it could send. It’s the most common bug with channels, and it compiles without a warning.
The two closing errors
Each end learns that the other is gone through a Result.
The receiver is gone.
let (tx, rx) = mpsc::channel();
drop(rx);
match tx.send(String::from("bonjour")) {
Ok(()) => println!("envoyé"),
Err(e) => println!("erreur : {e} · message rendu : {:?}", e.0),
}erreur : sending on a closed channel · message rendu : "bonjour"The message isn’t lost: SendError contains it, and e.0 hands it back. With .unwrap() instead of the match, it’s a panic:
thread 'main' (31640) panicked at unwrap_send.rs:6:16:
called `Result::unwrap()` on an `Err` value: SendError { .. }All senders are gone.
let (tx, rx) = mpsc::channel();
tx.send(1).unwrap();
drop(tx);
println!("{:?}", rx.recv());
match rx.recv() {
Ok(n) => println!("reçu : {n}"),
Err(e) => println!("erreur : {e}"),
}Ok(1)
erreur : receiving on a closed channelNote the order: the message sent before the close is still delivered. recv only returns Err once the queue is empty and the channel is closed. That is exactly the signal that ends the for loop.
sync_channel: a bounded channel
mpsc::channel() has no limit: send never blocks, and a producer faster than the consumer fills up memory. mpsc::sync_channel(n) bounds the queue to n messages. When it’s full, send waits:
let (tx, rx) = mpsc::sync_channel(1);
let debut = Instant::now();
let h = thread::spawn(move || {
for i in 1..=3 {
tx.send(i).unwrap();
println!("envoyé {i} après {} ms environ", debut.elapsed().as_millis() / 100 * 100);
}
});
thread::sleep(Duration::from_millis(100));
for n in rx {
println!(" reçu {n}");
thread::sleep(Duration::from_millis(100));
}
h.join().unwrap();envoyé 1 après 0 ms environ
reçu 1
envoyé 2 après 100 ms environ
reçu 2
envoyé 3 après 200 ms environ
reçu 3The first send goes through right away: the queue has one slot. The second waits until the receiver has taken the first. The producer moves at the consumer’s pace: that’s backpressure.
The non-blocking variants say why they fail:
let (tx, rx) = mpsc::sync_channel(1);
println!("{:?}", tx.try_send(1));
println!("{:?}", tx.try_send(2));
println!("{:?}", rx.try_recv());
println!("{:?}", rx.try_recv());
drop(tx);
println!("{:?}", rx.try_recv());Ok(())
Err(TrySendError::Full(..))
Ok(1)
Err(Empty)
Err(Disconnected)Empty: nothing for now, try again. Disconnected: nothing will ever come.
What the picture hides
- The receiver can’t be cloned.
rx.clone()gives E0599, “no method namedclonefound for structstd::sync::mpsc::Receiver<T>”. That’s the single consumer inmpsc. - It can’t be shared either. Two scoped threads borrowing the same
rxgive E0277, “Receiver<i32>cannot be shared between threads safely”:ReceiverisSendbut notSync, as seen in the previous article’s table. - Several workers:
Arc<Mutex<Receiver<T>>>. Each worker takes the lock, receives one message, releases the lock. Checked: two workers sharing the integers from 1 to 100 do total5050. - The message must be
Send. Sending anRcfrom a thread is refused: E0277, “Rc<i32>cannot be sent between threads safely”, with the note “required forSender<Rc<i32>>to implementSend”. - A channel doesn’t remove every way to block. There is no lock on the data any more, but two threads each waiting for a message from the other wait forever. The forgotten
txis the single-thread version of that. - A successful
senddoesn’t mean “received”.Ok(())means the message is in the queue. If the receiver goes away afterwards, the message is dropped along with the channel. - These are the standard library’s blocking channels. Asynchronous code uses other channels, built on the same ownership model.
asyncis the topic of the next volume.
Going further
- Volume 7, issue 03 of The Rust Loop, Channels, or share memory by communicating, which details message passing and ownership transferred through the channel (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). - The Rust Book: using message passing to transfer data between threads
- The standard library: the
mpscmodule,sync_channelandSendError