LockedResource
open class LockedResource<T>
A generic class that protects a resource of type T with a Lock.
The user of a LockedResource accesses the resource via a read or write
function. The resource itself is available only within the scope of the
passed-in function, during which time the appropriate lock is guaranteed
to be held.
-
Initializes a new
LockedResourceto protect the given resource using the specifiedLockMechanism.Declaration
Swift
public init(resource: T, lock mechanism: LockMechanism)Parameters
resourceThe resource to be protected with a lock.
mechanismA
LockMechanismvalue specifying the type of lock that will be used to protectresource. -
Executes the given function with a read lock held, returning its result.
Declaration
Swift
open func read<R>(_ fn: (T) -> R) -> RParameters
fnA function that will be executed with the read lock held. The protected resource is passed as a parameter to
operation, which may use it for reading only.Return Value
The result of calling
fn(). -
Executes the given function with the write lock held, returning its result.
Note
Whether or not
operationis an escaping function depends upon the underlying lock mechanism. Because it may escape in some implementations, it has to be declared@escapinghere to cover all cases.Declaration
Swift
open func write<R>(_ fn: (inout T) -> R) -> RParameters
operationA function that will be executed with the write lock held. The protected resource is passed as an
inoutparameter tooperationso that it may be mutated.Return Value
The result of calling
fn().
View on GitHub
LockedResource Class Reference