Module std.semaphore

Counting semaphore for concurrency control.

Limit the number of concurrent actors or tasks that can access a shared resource.

Examples

import std.semaphore;

fn main() {
    let sem = semaphore.new(3).expect("valid permit count");
    let lease = sem.lease();
    // critical section
    lease.close();
    sem.close();
}

Call clone() explicitly to share one permit count. Each returned handle closes independently; assigning a semaphore does not create another owner. lease() returns one capacity unit automatically at scope exit. Raw acquire() and release() support cross-task signalling; closing a raw semaphore handle does not return previously acquired capacity.

Contents

Functions

Function new

pub fn new(count: i64) -> Semaphore fails SemaphoreError

Create a new counting semaphore with the given number of permits.

Examples

import std.semaphore;

fn main() {
    let sem = semaphore.new(5).expect("valid permit count");
}

Types

Struct Semaphore

Fields

handle: SemaphoreHandle

Methods

fn acquire(self)

Block until a permit is available, then acquire it.

fn try_acquire(self) -> bool

Try to acquire a permit without blocking.

Returns true if a permit was acquired, false otherwise.

fn acquire_timeout(self, timeout: duration) -> bool

Try to acquire a permit, waiting up to timeout.

Returns true if a permit was acquired before the timeout.

fn release(self)

Release a previously acquired permit.

fn count(self) -> i64

Return the current number of available permits.

Struct Lease

Exclusive ownership of one acquired semaphore capacity unit.

Dropping or closing the lease returns its capacity exactly once. A lease can move to another task; it cannot be cloned. The semaphore may close while a lease remains alive.

Fields

semaphore: Semaphore

Enum SemaphoreError

A semaphore configuration that cannot be represented by the runtime.

Variants

InvalidPermitCount(i64)

Inherent methods

impl Lease

fn close(consume self)

Return this lease's capacity early.

impl Semaphore

fn lease(self) -> Lease

Acquire one capacity unit, returning an owned lease.

Scope exit, fault and cancellation return acquired capacity. While waiting, cancellation removes the pending acquisition. Raw acquire and release remain available for cross-task signalling.

fn clone(self) -> Semaphore

Create an independently owned handle to this semaphore.

Both handles share one permit count. Close each handle separately.

fn close(consume self)

Release this semaphore early.