Answer#
Go makes concurrency cheap and implicit: go f() starts a goroutine, channels connect them, sync.WaitGroup waits. Go goroutines are scheduled by the Go runtime on a few operating system threads. A Rust std::thread is one operating system thread, which costs more to create. For thousands of concurrent units that mostly wait on I/O, use async tasks with a runtime such as Tokio (see the thread on JavaScript promises); for a handful of CPU-bound workers, threads are the direct port.
| Go | Rust |
|---|---|
go f() | thread::spawn with a move closure, or tokio::spawn for async |
make(chan T) | let (tx, rx) = mpsc::channel::<T>(); |
ch <- v, <-ch | tx.send(v), rx.recv() |
close(ch) | drop every Sender; then recv returns Err and for v in rx ends |
for v := range ch | for v in rx |
| several goroutines reading one channel | share the receiver: Arc<Mutex<Receiver<T>>> |
sync.WaitGroup | keep the JoinHandles and call .join() on each |
sync.Mutex next to the data | Mutex<T> that owns the data |
select | crossbeam or Tokio's select! (not run here); try_recv for polling |
A worker pool that squares the numbers 1 to 10 and sums them, in Go (1.26.5):
func main() {
jobs := make(chan int)
results := make(chan int)
var wg sync.WaitGroup
for w := 0; w < 3; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobs {
results <- j * j
}
}()
}
go func() {
for n := 1; n <= 10; n++ {
jobs <- n
}
close(jobs)
}()
go func() { wg.Wait(); close(results) }()
total := 0
for r := range results {
total += r
}
fmt.Println("sum of squares 1..=10 =", total)
}sum of squares 1..=10 = 385And in Rust (1.93.0), with standard library threads and channels:
use std::sync::mpsc;
use std::thread;
fn main() {
let (job_tx, job_rx) = mpsc::channel::<u64>();
let job_rx = std::sync::Arc::new(std::sync::Mutex::new(job_rx));
let (res_tx, res_rx) = mpsc::channel::<u64>();
let workers: Vec<_> = (0..3)
.map(|_| {
let rx = std::sync::Arc::clone(&job_rx);
let tx = res_tx.clone();
thread::spawn(move || loop {
let job = rx.lock().unwrap().recv(); // the lock is released at the end of this statement
match job {
Ok(n) => tx.send(n * n).unwrap(),
Err(_) => break, // channel closed: like `for j := range jobs` ending
}
})
})
.collect();
drop(res_tx);
for n in 1..=10 {
job_tx.send(n).unwrap();
}
drop(job_tx); // Go: close(jobs)
let mut total = 0;
for r in res_rx {
total += r;
}
for w in workers {
w.join().unwrap();
}
println!("sum of squares 1..=10 = {total}");
}sum of squares 1..=10 = 385The sum is the same on every run because addition does not care about the order in which workers finish. Three details were forced by Rust: the receiver is shared through Arc<Mutex<..>> because mpsc has exactly one consumer; the original res_tx is dropped so that the results channel ends once the workers finish; and job_tx is dropped to signal "no more jobs", which is how Rust spells close.
How to do it#
- Decide per goroutine: CPU-bound worker (thread), or I/O-bound and numerous (async task).
- Port each channel to an
mpscchannel. Usesync_channel(n)for a bounded channel that blocks the sender when full, like a buffered Go channel with capacityn. - Replace "close the channel" with "drop all senders", and make sure no spare
Senderlives longer than you expect: a forgotten clone keeps the receiver waiting forever. - Replace
WaitGroupwith the vector ofJoinHandles. Replace shared variables withMutex<T>or atomics, or better with messages. - For parallel loops over data, consider the
rayoncrate instead of a hand-made pool; it was not run for this thread.
Common mistakes#
- Spawning one OS thread per item for a large number of items. Use a bounded pool or async tasks.
- Holding the
Mutexlock on the shared receiver while doing the work. In the code above the lock is held only during therecv()call, so the workers do their work in parallel. - Dropping a
JoinHandlewithout joining and assuming the thread has finished. Data may be lost whenmainreturns.
Related questions#
Does Rust detect deadlocks in channel code?#
No. A receiver waiting for a sender that is never dropped waits forever, as in Go (where the runtime may report "all goroutines are asleep").
Are goroutines faster than threads?#
Creating them is cheaper. How much it matters depends on the program, and this thread did not measure it.
Sources#
- The Rust Book, "Using Message Passing to Transfer Data Between Threads": https://doc.rust-lang.org/book/ch16-02-message-passing.html
std::sync::mpsc: https://doc.rust-lang.org/std/sync/mpsc/index.html