Agentic.Concurrency.Semaphore (agentic v0.2.2)

Copy Markdown

Bounded concurrency semaphore using a GenServer.

Ported from SCE. Limits the number of concurrent tasks that can hold permits. Automatically releases permits when the holding process crashes.

Usage

{:ok, sem} = Semaphore.start_link(limit: 5)
:ok = Semaphore.acquire(sem)
# do work
:ok = Semaphore.release(sem)

Or with automatic release:

Semaphore.with_permit(sem, fn ->
  # do work — permit auto-released on return or crash
end)

Summary

Functions

Acquire a permit. Blocks if none available. Returns :ok. Times out after 5 seconds by default.

Returns a specification to start this module under a supervisor.

Get the concurrency limit.

Release a permit. Returns :ok.

Start a semaphore with the given concurrency limit.

Get current stats.

Execute a function with an automatically managed permit.

Types

t()

@type t() :: %Agentic.Concurrency.Semaphore{
  available: non_neg_integer(),
  limit: pos_integer(),
  monitors: %{required(reference()) => pid()},
  queue: :queue.queue(),
  stats: %{total_acquired: non_neg_integer(), total_released: non_neg_integer()}
}

Functions

acquire(sem, timeout \\ 5000)

Acquire a permit. Blocks if none available. Returns :ok. Times out after 5 seconds by default.

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

limit(sem)

Get the concurrency limit.

release(sem)

Release a permit. Returns :ok.

start_link(opts)

Start a semaphore with the given concurrency limit.

stats(sem)

Get current stats.

with_permit(sem, fun)

Execute a function with an automatically managed permit.