Alambic.Semaphore (alambic v1.1.0)
A simple semaphore implementation, useful when you need quick control around resource access and do not want to resort to the full OTP artillery or complex process pooling.
This semaphore is implemented as a GenServer
.
If you need to start a named Semaphore
as part of a supervision
tree, you should use directly the GenServer.start/start_link
functions passing the required max
as argument.
Link to this section Summary
Functions
Acquire a slot in the semaphore. Will block until a slot is available or the semaphore is destroyed.
Returns a specification to start this module under a supervisor.
Create a semaphore with max
slots.
Create a semaphore with max
slots. The semaphore is linked to
the current process.
Destroy a semaphore. Clients waiting on acquire
will receive
an :error
response.
Return true
if no slot is available, false
otherwise.
Callback implementation for GenServer.init/1
.
Release a slot from the semaphore. :error
is returned if no slot
is currently acquired.
Try to acquire a slot in the semaphore but does not block if no slot
is available. Returns true
if a slot was acquired, false
otherwise.
Link to this section Types
Specs
t() :: %Alambic.Semaphore{id: pid()}
Link to this section Functions
acquire(_)
Specs
acquire(t()) :: :ok | :error
Acquire a slot in the semaphore. Will block until a slot is available or the semaphore is destroyed.
Example
iex> s = Alambic.Semaphore.create(10)
iex> Alambic.Semaphore.acquire(s)
:ok
child_spec(init_arg)
Returns a specification to start this module under a supervisor.
See Supervisor
.
create(max)
Specs
Create a semaphore with max
slots.
iex> s = Alambic.Semaphore.create(3)
iex> is_nil(s.id)
false
create_link(max)
Specs
Create a semaphore with max
slots. The semaphore is linked to
the current process.
iex> s = Alambic.Semaphore.create_link(3)
iex> Alambic.Semaphore.destroy(s)
:ok
destroy(semaphore)
Specs
destroy(t()) :: :ok
Destroy a semaphore. Clients waiting on acquire
will receive
an :error
response.
full?(_)
Specs
full?(t()) :: true | false
Return true
if no slot is available, false
otherwise.
Example
iex> s = Alambic.Semaphore.create(1)
iex> false = Alambic.Semaphore.full?(s)
iex> Alambic.Semaphore.acquire(s)
iex> Alambic.Semaphore.full?(s)
true
init(max)
Callback implementation for GenServer.init/1
.
release(_)
Specs
release(t()) :: :ok | :error
Release a slot from the semaphore. :error
is returned if no slot
is currently acquired.
Example
iex> s = Alambic.Semaphore.create(1)
iex> Alambic.Semaphore.acquire(s)
iex> false = Alambic.Semaphore.try_acquire(s)
iex> Alambic.Semaphore.release(s)
iex> Alambic.Semaphore.try_acquire(s)
true
try_acquire(_)
Specs
try_acquire(t()) :: true | false
Try to acquire a slot in the semaphore but does not block if no slot
is available. Returns true
if a slot was acquired, false
otherwise.
Example
iex> s = Alambic.Semaphore.create(1)
iex> true = Alambic.Semaphore.try_acquire(s)
iex> Alambic.Semaphore.try_acquire(s)
false