Threads and Message Passing
2026-10-24
This module: Concurrent programming with threads
std cratesthread::spawn takes FnOnce() -> T, returns JoinHandle<T>handle.join() returns thread::Result<T>main() exitErr variant on JoinHandle
Any is a trait to emulate dynamic typingSend means safe to move between threads'static lifetimeT = Result<S,E>
Ok(Err(err)) for err: EWhich of these is true?
send takes ownership of the message argumentthread::spawn need not satisfy 'staticpanic!() in a thread will terminate the programRespond at: https://PollEv.com/davidbindel252 or send davidbindel252 to 22333
std::markerSized)Copy)Send and SyncThread communication involves ownership transfer
drop in anotherA Send type is safe to transfer across threads.
String, TCPStream, Vec are SendReceiver<usize> and Cell<usize>!Send: Rc<String>, raw pointersA type T is Sync if &T is Send
Sync!String, TCPStream, Vec are Send!Sync: Receiver<usize> and Cell<usize>!Sync: Rc<String>, raw pointers'static'static means “contains no non-static references”
'static boundHow do we get static data?
leak on containers (Box, String, Vec)'static mutable ref or slice to contents'static data!thread::scope completes, all threads guaranteed to be joinedChannels are unidirectional – how to get replies?
Ack pattern: send data containing a Sendersends data on the receivercloneduse std::sync::mpsc::{channel, Receiver, RecvError, Sender};
use std::thread;
struct Command(String, Sender<String>);
fn echo_client(id: usize, tx: Sender<Command>) {
let (response_tx, response_rx) = channel();
tx.send(Command(format!("Ping {id}"), response_tx)).unwrap();
println!("{id} received: {}", response_rx.recv().unwrap());
}
fn echo_server(server_rx: Receiver<Command>) -> Result<(), RecvError> {
loop {
let Command(s, tx) = server_rx.recv()?;
println!("Server received: {s}");
tx.send(s).unwrap();
}
}fn main() {
let (channel_in, channel_out1) = channel();
let (channel_in2, channel_out2) = channel();
let (channel_in3, channel_out) = channel();
thread::spawn(move || {
stage(channel_out1, channel_in2, |x: usize| 2*x)
});
thread::spawn(move || {
stage(channel_out2, channel_in3, |x: usize| x+1)
});
channel_in.send(5).expect("Channel died prematurely");
channel_in.send(10).expect("Channel died prematurely");
assert_eq!(channel_out.recv().unwrap(), 11);
assert_eq!(channel_out.recv().unwrap(), 21);
}channel produces an asynchronous channel
send never blocks on calling threadsync_channel(b) produces a synchronous channel
b messagessend blocks until there is buffer spacedeque and MPMC queuesWhat is the default channel type from std::mpsc::channel?
sendRespond at: https://PollEv.com/davidbindel252 or send davidbindel252 to 22333
Want to understand performance of networked applications
Hard to do in practice. Simulate!
https://github.coecis.cornell.edu/cs4414-f26/p4-netsim