pub struct Semaphore { /* private fields */ }
Expand description
A counting, blocking, semaphore.
Semaphores are a form of atomic counter where access is only granted if the counter is a positive value. Each acquisition will block the calling thread until the counter is positive, and each release will increment the counter and unblock any threads if necessary.
§Examples
use std_semaphore::Semaphore;
// Create a semaphore that represents 5 resources
let sem = Semaphore::new(5);
// Acquire one of the resources
sem.acquire();
// Acquire one of the resources for a limited period of time
{
let _guard = sem.access();
// ...
} // resources is released here
// Release our initially acquired resource
sem.release();
Implementations§
Source§impl Semaphore
impl Semaphore
Sourcepub fn new(count: isize) -> Semaphore
pub fn new(count: isize) -> Semaphore
Creates a new semaphore with the initial count specified.
The count specified can be thought of as a number of resources, and a
call to acquire
or access
will block until at least one resource is
available. It is valid to initialize a semaphore with a negative count.
Sourcepub fn acquire(&self)
pub fn acquire(&self)
Acquires a resource of this semaphore, blocking the current thread until it can do so.
This method will block until the internal count of the semaphore is at least 1.
Sourcepub fn release(&self)
pub fn release(&self)
Release a resource from this semaphore.
This will increment the number of resources in this semaphore by 1 and
will notify any pending waiters in acquire
or access
if necessary.
Sourcepub fn access(&self) -> SemaphoreGuard<'_>
pub fn access(&self) -> SemaphoreGuard<'_>
Acquires a resource of this semaphore, returning an RAII guard to release the semaphore when dropped.
This function is semantically equivalent to an acquire
followed by a
release
when the guard returned is dropped.