FAQ - Help and questions

How do goroutines, channels and WaitGroup map to Rust threads and channels?

#porting#golang#concurrencypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A goroutine becomes a thread or a Tokio task, a channel becomes an mpsc channel, and closing a channel becomes dropping every sender. Rust channels have one consumer, so a worker pool shares the receiver behind a Mutex. Joining thread handles replaces WaitGroup, and the compiler checks what each thread may touch.

Checked with rustc 1.93.0, Go 1.26.5, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

GoRust
go f()thread::spawn with a move closure, or tokio::spawn for async
make(chan T)let (tx, rx) = mpsc::channel::<T>();
ch <- v, <-chtx.send(v), rx.recv()
close(ch)drop every Sender; then recv returns Err and for v in rx ends
for v := range chfor v in rx
several goroutines reading one channelshare the receiver: Arc<Mutex<Receiver<T>>>
sync.WaitGroupkeep the JoinHandles and call .join() on each
sync.Mutex next to the dataMutex<T> that owns the data
selectcrossbeam 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):

go
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)
}
text
sum of squares 1..=10 = 385

And in Rust (1.93.0), with standard library threads and channels:

src/main.rsrust
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}");
}
text
sum of squares 1..=10 = 385

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

  1. Decide per goroutine: CPU-bound worker (thread), or I/O-bound and numerous (async task).
  2. Port each channel to an mpsc channel. Use sync_channel(n) for a bounded channel that blocks the sender when full, like a buffered Go channel with capacity n.
  3. Replace "close the channel" with "drop all senders", and make sure no spare Sender lives longer than you expect: a forgotten clone keeps the receiver waiting forever.
  4. Replace WaitGroup with the vector of JoinHandles. Replace shared variables with Mutex<T> or atomics, or better with messages.
  5. For parallel loops over data, consider the rayon crate 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 Mutex lock on the shared receiver while doing the work. In the code above the lock is held only during the recv() call, so the workers do their work in parallel.
  • Dropping a JoinHandle without joining and assuming the thread has finished. Data may be lost when main returns.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet