Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 5: Concurrency, Closures & Top Gotchas
RUST

Part 5: Concurrency, Closures & Top Gotchas

Review Rust threads, Send and Sync, closures, shared state, concurrency patterns, and common language gotchas.

1. Threads

use std::thread;
let handle = thread::spawn(|| { println!("child"); });
handle.join().unwrap();
  • thread::spawn takes an 'static closure + Send return.
  • move closures capture by value so the worker owns access.
  • std::sync::mpsc channels for message passing.

2. Send & Sync

MarkerMeaning
Sendtype can be moved to another thread safely
Syncreferences to it can be shared across threads
  • Rc is not Send/Sync; Arc is.
  • !Send types (Rc, *const T, raw pointers) block moving cross-thread (compile-time).
  • Proper Send/Sync is checked at compile time.

3. Mutex & Arc

let counter = Arc::new(Mutex::new(0));
let c = Arc::clone(&counter);
thread::spawn(move || {
    let mut n = c.lock().unwrap();
    *n += 1;
});
  • Arc shares ownership; Mutex provides locking; lock() gives MutexGuard.
  • Poisons on panic: lock() returns Err after a panic inside the guard.

4. async/await — the lightweight model

async fn fetch() -> String {
    "ok".to_string()
}
// .await in async context
  • tokio / async-std runtime drives futures.
  • async fn returns a Future; .await suspends, yielding to the runtime.
  • Send + 'static requirement when spawning async tasks.

5. Closures

  • Closures infer capture: by reference by default, move for ownership.
  • Fn/FnMut/FnOnce trait families — how the closure uses captures.
  • Common in iterators: .filter(|x| ...), .map(|x| ...).

6. Gotcha sheet — interview fast-refresh

  • s.len() is bytes, not chars.
  • Vec growth: index vs .get().
  • String no linear indexing.
  • Box<dyn Trait> vs generics.
  • Rc in multi-thread; Arc needed.
  • Borrow checker fights — share small integers via clones rather than refs.
  • loop vs while let vs recursion.
  • Lifetime 'static on traits: use Box<dyn Trait + 'static> vs lifetime-bound traits.

7. Interview checkpoint

  • Send vs Sync semantics — quick one-liner.
  • Rc vs Arc; when Mutex.
  • async vs threads — IO-bound vs CPU-bound.
  • Closure capture rules; move closure.
  • The gotcha sheet — the memory-safe exam favorite.

My Private Notes

Notes are auto-saved locally to this device.