Please help understand the problem with implementing a semaphore

⚓ Rust    📅 2026-04-04    👤 surdeus    👁️ 1      

surdeus

I am trying to implement a semaphore for the first time, started with a basic version, encountered an error, that I am struggling to understand.

const NUMBER_OF_RESOURCES: u32 = 1;

pub struct Semaphore {
counter: AtomicU32,
}

impl Semaphore {
pub fn new() -> Self {
Self {
counter: AtomicU32::new(NUMBER_OF_RESOURCES),
}
}

pub fn signal(&self) {
    assert!(self.counter.load(Relaxed) < NUMBER_OF_RESOURCES);
    if self.counter.fetch_add(1, Release) == 0 {
        wake_one(&self.counter);
    }
}

pub fn wait(&self) {
    while self.counter.load(Relaxed) == 0 {
        wait(&self.counter, 0);
    }
    self.counter.fetch_sub(1, Acquire);
}

}

I use atomic-wait crate.

The error: threads start to decrement and increment semaphore normally, then one of the threads encounter u32::MAX counter instead of 1, when calls wait() method. Then, obviously, several threads are able to access the semaphore simultaneously. I am trying to understand what is happenning for educational purposes. Would be very grateful for any suggestion.

3 posts - 2 participants

Read full topic

🏷️ Rust_feed