Systems Advanced

19  Channels

Instead of sharing memory, pass messages. An mpsc channel has many senders and one receiver. When every sender is dropped, iterating the receiver ends -- that is how the loop knows to stop.

Step 1 / 2

In sum_over_channel, send every number from a worker thread and sum them as they arrive on the receiver.

Hints
  • let (tx, rx) = mpsc::channel(); then tx.send(n) in the thread.
  • for n in rx { total += n; } ends when the sender is dropped (the thread finishes).
19_channels.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
use std::sync::mpsc;
use std::thread;

fn sum_over_channel(nums: Vec<i64>) -> i64 {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        for n in nums {
            tx.send(n).unwrap();
        }
    });
    let mut total = 0;
    for n in rx {
        total += n;
    }
    total
}