Struct glommio::sync::Semaphore

source ·
pub struct Semaphore { /* private fields */ }
Expand description

An implementation of semaphore that doesn’t use helper threads, condition variables, and is friendly to single-threaded execution.

Implementations§

source§

impl Semaphore

source

pub fn new(avail: u64) -> Semaphore

Creates a new semaphore with the specified amount of units

§Examples
use glommio::sync::Semaphore;

let _ = Semaphore::new(1);
source

pub fn available(&self) -> u64

Returns the amount of units currently available in this semaphore

§Examples
use glommio::sync::Semaphore;

let sem = Semaphore::new(1);
assert_eq!(sem.available(), 1);
source

pub async fn acquire_permit(&self, units: u64) -> Result<Permit<'_>, ()>

Suspends until a permit can be acquired with the specified amount of units.

Returns Err() if the semaphore is closed during the wait.

Similar to acquire_static_permit, except that it requires the permit never to be passed to contexts that require a static lifetime. As this is cheaper than acquire_static_permit, it is useful in situations where the permit tracks an asynchronous operation whose lifetime is simple and well-defined.

§Examples
use glommio::{sync::Semaphore, LocalExecutor};

let sem = Semaphore::new(1);

let ex = LocalExecutor::default();
ex.run(async move {
    {
        let permit = sem.acquire_permit(1).await.unwrap();
        // once it is dropped it can be acquired again
        // going out of scope will drop
    }
    let _guard = sem.acquire_permit(1).await.unwrap();
});
source

pub async fn acquire_static_permit( self: &Rc<Self>, units: u64 ) -> Result<StaticPermit, ()>

Suspends until a permit can be acquired with the specified amount of units.

Returns Err() if the semaphore is closed during the wait.

Similar to acquire_permit, except that it requires the semaphore to be contained in an Rc. This is useful in situations where the permit tracks a long-lived asynchronous operation whose lifetime is complex.

§Examples
use glommio::{sync::Semaphore, timer::sleep, LocalExecutor};
use std::{rc::Rc, time::Duration};

let sem = Rc::new(Semaphore::new(1));

let ex = LocalExecutor::default();
ex.run(async move {
    {
        let permit = sem.acquire_static_permit(1).await.unwrap();
        glommio::spawn_local(async move {
            let _guard = permit;
            sleep(Duration::from_secs(1)).await;
        })
        .detach();
        // once it is dropped it can be acquired again
        // going out of scope will drop
    }
    let _guard = sem.acquire_permit(1).await.unwrap();
});
source

pub async fn acquire(&self, units: u64) -> Result<(), ()>

Acquires the specified amount of units from this semaphore.

The caller is then responsible to release units. Whenever possible, prefer acquire_permit().

§Examples
use glommio::{sync::Semaphore, LocalExecutor};

let sem = Semaphore::new(1);

let ex = LocalExecutor::default();
ex.run(async move {
    sem.acquire(1).await.unwrap();
    sem.signal(1); // Has to be signaled explicitly. Be careful
});
source

pub fn try_acquire(&self, units: u64) -> Result<bool, ()>

Acquires the given number of units, if they are available, and returns immediately, with the value true, reducing the number of available units by the given amount.

If insufficient units are available then this method will return immediately with the value false and the number of available permits is unchanged.

This method does not suspend.

The caller is then responsible to release units. Whenever possible, prefer try_acquire_permit.

§Errors

If semaphore is closed Err(io::Error(BrokenPipe)) will be returned.

§Examples
use glommio::{sync::Semaphore, LocalExecutor};

let sem = Semaphore::new(1);

let ex = LocalExecutor::default();

ex.run(async move {
    assert!(sem.try_acquire(1).unwrap());
    sem.signal(1); // Has to be signaled explicitly. Be careful
});
source

pub fn try_acquire_permit(&self, units: u64) -> Result<Permit<'_>, ()>

Acquires the given number of units, if they are available, and returns immediately, with the RAAI guard, reducing the number of available units by the given amount.

The Permit is bound to the lifetime of the current reference of this semaphore. If you need it to live longer, consider using try_acquire_static_permit.

If insufficient units are available then this method will return Err and the number of available permits is unchanged.

This method does not suspend.

§Errors

If semaphore is closed Err(GlommioError::Closed(ResourceType::Semaphore { .. })) will be returned. If semaphore does not have sufficient amount of units

Err(GlommioError::WouldBlock(ResourceType::Semaphore {
    requested: u64,
    available: u64
}))

will be returned.

§Examples
let sem = Semaphore::new(1);
let permit = sem.try_acquire_permit(1).unwrap();
let permit2 = sem.try_acquire_permit(1).unwrap_err();
source

pub fn try_acquire_static_permit( self: &Rc<Self>, units: u64 ) -> Result<StaticPermit, ()>

Acquires the given number of units, if they are available, and returns immediately, with the RAII guard, reducing the number of available units by the given amount.

This function returns a StaticPermit and is suitable for 'static contexts. If your lifetimes are simple, and you don’t need the permit to outlive your context, consider using try_acquire_permit instead.

If insufficient units are available then this method will return Err and the number of available permits is unchanged.

This method does not suspend.

§Errors

If semaphore is closed Err(GlommioError::Closed(ResourceType::Semaphore { .. })) will be returned. If semaphore does not have sufficient amount of units

Err(GlommioError::WouldBlock(ResourceType::Semaphore {
    requested: u64,
    available: u64
}))

will be returned.

§Examples
let sem = Rc::new(Semaphore::new(1));
let permit = sem.try_acquire_static_permit(1).unwrap();
let permit2 = sem.try_acquire_static_permit(1).unwrap_err();
source

pub fn signal(&self, units: u64)

Signals the semaphore to release the specified amount of units.

This needs to be paired with a call to Semaphore::acquire(). You should not call this if the units were acquired with Semaphore::acquire_permit().

§Examples
use glommio::{sync::Semaphore, LocalExecutor};

let sem = Semaphore::new(0);

let ex = LocalExecutor::default();
ex.run(async move {
    // Note that we can signal to expand to more units than the original capacity had.
    sem.signal(1);
    sem.acquire(1).await.unwrap();
});
source

pub fn close(&self)

Closes the semaphore

All existing waiters will return Err(), and no new waiters are allowed.

§Examples
use glommio::{sync::Semaphore, LocalExecutor};

let sem = Semaphore::new(0);

let ex = LocalExecutor::default();
ex.run(async move {
    // Note that we can signal to expand to more units than the original capacity had.
    sem.close();
    if let Ok(_) = sem.acquire(1).await {
        panic!("a closed semaphore should have errored");
    }
});

Trait Implementations§

source§

impl Debug for Semaphore

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Semaphore

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more