SemaphoreState

Trait SemaphoreState 

Source
pub trait SemaphoreState {
    type Params;
    type Permit;

    // Required methods
    fn acquire(
        &mut self,
        params: Self::Params,
    ) -> Result<Self::Permit, Self::Params>;
    fn release(&mut self, permit: Self::Permit);
}
Expand description

The trait defining how semaphores behave.

The usage of this state is as follows:

fn get_permit<S: SemaphoreState>(s: &Mutex<S>, mut params: S::Params) -> S::Permit {
    loop {
        let mut s = s.lock().unwrap();
        match s.acquire(params) {
            Ok(permit) => break permit,
            Err(p) => params = p,
        }

        // sleep/spin/yield until time to try again
    }
}

fn return_permit<S: SemaphoreState>(s: &Mutex<S>, permit: S::Permit) {
    s.lock().unwrap().release(permit);
}

Required Associated Types§

Source

type Params

What type is used to request permits.

An example of this could be usize for a counting semaphore, if you want to support acquire_many type requests.

Source

type Permit

The type representing the current permit allocation.

If you have a counting semaphore, this could be the number of permits acquired. If this is more like a connection pool, this could be a specific object allocation.

Required Methods§

Source

fn acquire( &mut self, params: Self::Params, ) -> Result<Self::Permit, Self::Params>

Acquire a permit given the params.

§Errors

If a permit could not be acquired with the given params, return an error and the original params back.

Source

fn release(&mut self, permit: Self::Permit)

Return the permit back to the semaphore.

Note: This is not guaranteed to be called for every acquire call. Permits can be modified or forgotten, or created at will.

Implementors§