Struct std::sync::Semaphore [] [src]

pub struct Semaphore {
    // some fields omitted
}
Unstable (semaphore #27798)

: the interaction between semaphores and the acquisition/release of resources is currently unclear

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

#![feature(semaphore)] fn main() { use std::sync::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(); }
#![feature(semaphore)]

use std::sync::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();

Methods

impl Semaphore

fn new(count: isize) -> Semaphore

Unstable (semaphore #27798)

: the interaction between semaphores and the acquisition/release of resources is currently unclear

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.

fn acquire(&self)

Unstable (semaphore #27798)

: the interaction between semaphores and the acquisition/release of resources is currently unclear

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.

fn release(&self)

Unstable (semaphore #27798)

: the interaction between semaphores and the acquisition/release of resources is currently unclear

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.

fn access(&self) -> SemaphoreGuard

Unstable (semaphore #27798)

: the interaction between semaphores and the acquisition/release of resources is currently unclear

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.