View Source spinlock (spinlock v0.2.1)
Summary
Functions
Acquires a lock for the current process.
Creates a new spinlock instance with the given options.
Releases an already acquired lock.
Returns the status of the given lock.
Executes the given function in a transaction.
Types
-type lock_id() :: pos_integer().
-type option() :: {max_retry, pos_integer()} | {atomics_ref, atomics:atomics_ref()}.
-type spinlock() :: #spinlock{}.
Functions
-spec acquire(Lock :: #spinlock{}) -> lock_id().
Acquires a lock for the current process.
This will busy-wait until a lock can be acquired, or a maximum configured number of attemps is reached. Returnedlock_id
is used to release the lock later.
-spec new() -> #spinlock{}.
Equivalent to new([]).
-spec new(Options :: [option()]) -> #spinlock{}.
Creates a new spinlock instance with the given options.
Possible options are:{max_retry, MaxRetry}
The lock is forecibly released after
MaxRetry
number of attempts.{atomics_ref, AtomicsRef}
Uses the first two index of the given atomics array to store the state of the lock. If you want to use spinlock to implement transactions for an atomics array, you can use this option to avoid creating an extra atomics array.
-spec release(Lock :: #spinlock{}, LockId :: lock_id()) -> ok | {error, already_released | invalid_lock_id}.
Releases an already acquired lock.
This will release the lock for the given LockId. Returnsok
if the lock is successfully released. Otherwise returns {error, already_released}
if the lock is already released or {error, invalid_lock_state}
if the given LockId has never been acquired.
-spec status(Lock :: #spinlock{}) ->
#{released => non_neg_integer(), is_locked => boolean(), waiting => non_neg_integer()}.
Returns the status of the given lock.
You can use this function for debugging purposes, to check the current status of the lock, and to see how many process are waiting to acquire the lock.-spec transaction(Lock :: #spinlock{}, Fun :: fun(() -> any())) -> any().
Executes the given function in a transaction.
Acquires the lock, executes the given function, and releases the lock when the function has returend. The lock is released even if the function fails with an exception.