Counting semaphore adapter using Foundation.Semaphore.Counting.
This adapter provides connection/concurrency limiting using an ETS-backed counting semaphore. It's designed for limiting concurrent HTTP connections or other resource access patterns.
Example
# Initialize a semaphore with a limit of 10 concurrent operations
Counting.init(:http_pool, 10)
# Execute a function while holding a permit
result = Counting.with_permit(:http_pool, 5_000, fn ->
make_http_request()
end)
# Handle timeout
case Counting.with_permit(:http_pool, 100, fn -> slow_operation() end) do
{:error, :timeout} -> {:error, :too_busy}
result -> result
end
Summary
Functions
Attempt to acquire a permit from the semaphore.
Get the number of available permits.
Initialize a named semaphore with a given limit.
Release a previously acquired permit back to the semaphore.
Execute a function while holding a semaphore permit.
Functions
Attempt to acquire a permit from the semaphore.
Uses a spin-wait loop with short sleeps to attempt acquisition within the specified timeout.
Get the number of available permits.
Returns the difference between the configured limit and the current count.
Initialize a named semaphore with a given limit.
The semaphore will be created in the adapter's registry and its limit will be stored for later reference.
Release a previously acquired permit back to the semaphore.
Execute a function while holding a semaphore permit.
Acquires a permit, executes the function, and releases the permit.
If the permit cannot be acquired within the timeout, returns {:error, :timeout}.
The permit is always released, even if the function raises an exception.