rust 64 lines · 9 steps

Building a counting semaphore in Rust

A Mutex plus a Condvar caps concurrency, with a Permit that releases automatically on drop.

Explained by highlit
1use std::collections::VecDeque;
2use std::sync::{Arc, Condvar, Mutex};
3use std::time::{Duration, Instant};
4 
5pub struct Semaphore {
6 inner: Mutex<State>,
7 available: Condvar,
8}
9 
10struct State {
11 permits: usize,
12 waiters: VecDeque<()>,
13}
14 
15pub struct Permit {
16 sem: Arc<Semaphore>,
17}
18 
19impl Semaphore {
20 pub fn new(max_in_flight: usize) -> Arc<Self> {
21 Arc::new(Semaphore {
22 inner: Mutex::new(State {
23 permits: max_in_flight,
24 waiters: VecDeque::new(),
25 }),
26 available: Condvar::new(),
27 })
28 }
29 
30 pub fn acquire(self: &Arc<Self>) -> Permit {
31 let mut state = self.inner.lock().unwrap();
32 while state.permits == 0 {
33 state = self.available.wait(state).unwrap();
34 }
35 state.permits -= 1;
36 Permit { sem: Arc::clone(self) }
37 }
38 
39 pub fn try_acquire_timeout(self: &Arc<Self>, timeout: Duration) -> Option<Permit> {
40 let deadline = Instant::now() + timeout;
41 let mut state = self.inner.lock().unwrap();
42 while state.permits == 0 {
43 let now = Instant::now();
44 if now >= deadline {
45 return None;
46 }
47 let (guard, result) = self.available.wait_timeout(state, deadline - now).unwrap();
48 state = guard;
49 if result.timed_out() && state.permits == 0 {
50 return None;
51 }
52 }
53 state.permits -= 1;
54 Some(Permit { sem: Arc::clone(self) })
55 }
56}
57 
58impl Drop for Permit {
59 fn drop(&mut self) {
60 let mut state = self.sem.inner.lock().unwrap();
61 state.permits += 1;
62 self.sem.available.notify_one();
63 }
64}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Pairing a Mutex with a Condvar lets threads sleep until shared state changes instead of busy-waiting.
  2. 2RAII (a Drop impl) makes resource release automatic and exception-safe, so permits can never leak.
  3. 3Condition predicates must be rechecked in a loop because waits can wake spuriously or lose the race to another thread.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a counting semaphore in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code