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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Pairing a Mutex with a Condvar lets threads sleep until shared state changes instead of busy-waiting.
- 2RAII (a Drop impl) makes resource release automatic and exception-safe, so permits can never leak.
- 3Condition predicates must be rechecked in a loop because waits can wake spuriously or lose the race to another thread.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-counting-semaphore-in-rust-explained-rust-1df4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.