CodingNeed.

Production engineering workshop · 45 MIN

Rust · Share ownership without hiding failures

Thread safety and correct failure handling are separate responsibilities.

Move values into worker closures when ownership is exclusive. Use Arc only when ownership must be shared. Mutex makes mutation mutually exclusive, but poisoning is still a possible failure state if a holder panics. Join every worker to observe panics. Keep lock scope short and avoid holding a synchronous lock across await. This sample uses scoped threads and a borrowed mutex to avoid unnecessary Arc allocation.

First reproduce the normal path. Then force a failure at each boundary and inspect what remains true.

Read the example

use std::sync::Mutex;
use std::thread;

fn total(deltas: &[i64]) -> Result<i64, String> {
    let sum = Mutex::new(0_i64);
    thread::scope(|scope| {
        let handles: Vec<_> = deltas.chunks(64).map(|chunk| {
            let shared = &sum;
            scope.spawn(move || -> Result<(), String> {
                let subtotal: i64 = chunk.iter().sum();
                let mut guard = shared.lock().map_err(|_| "poisoned lock")?;
                *guard += subtotal;
                Ok(())
            })
        }).collect();
        let mut failure = None;
        for handle in handles {
            match handle.join() {
                Ok(Ok(())) => {},
                Ok(Err(e)) => { failure = Some(e); },
                Err(_) => { failure = Some("worker panicked".to_string()); }
            }
        }
        match failure { Some(e) => Err(e), None => Ok(()) }
    })?;
    sum.into_inner().map_err(|_| "poisoned lock".to_string())
}
fn main() { println!("{:?}", total(&[3, -1, 4])); }
Check the expected output
Review the behavior in the stated project environment.

Your challenge

Create a Rust binary crate. Run this scoped-thread counter, then write tests for empty input and negative deltas. Add a deliberate worker panic in a test and observe how joining reports it. Explain when an asynchronous service should use message passing instead.

Solution cost: O(n) additions; thread startup can outweigh parallel gains. time · O(n/64) thread handles and stacks; bound this in production. space

Common trap

This teaching implementation spawns one thread per chunk; production workloads need bounded scheduling. Mutex does not eliminate deadlocks.

Study the project implementation
use std::sync::Mutex;
use std::thread;

fn total(deltas: &[i64]) -> Result<i64, String> {
    let sum = Mutex::new(0_i64);
    thread::scope(|scope| {
        let handles: Vec<_> = deltas.chunks(64).map(|chunk| {
            let shared = &sum;
            scope.spawn(move || -> Result<(), String> {
                let subtotal: i64 = chunk.iter().sum();
                let mut guard = shared.lock().map_err(|_| "poisoned lock")?;
                *guard += subtotal;
                Ok(())
            })
        }).collect();
        let mut failure = None;
        for handle in handles {
            match handle.join() {
                Ok(Ok(())) => {},
                Ok(Err(e)) => { failure = Some(e); },
                Err(_) => { failure = Some("worker panicked".to_string()); }
            }
        }
        match failure { Some(e) => Err(e), None => Ok(()) }
    })?;
    sum.into_inner().map_err(|_| "poisoned lock".to_string())
}
fn main() { println!("{:?}", total(&[3, -1, 4])); }

Further reading: Official documentation

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.