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 LockedResource to protect the given resource using the specified LockMechanism.

    Declaration

    Swift

    public init(resource: T, lock mechanism: LockMechanism)

    Parameters

    resource

    The resource to be protected with a lock.

    mechanism

    A LockMechanism value specifying the type of lock that will be used to protect resource.

  • Initializes a new LockedResource to protect the given resource using the specified Lock.

    Declaration

    Swift

    public init(resource: T, lock: Lock)

    Parameters

    resource

    The resource to be protected with lock.

    lock

    The Lock instance that will be used to protect resource.

  • Executes the given function with a read lock held, returning its result.

    Declaration

    Swift

    open func read<R>(_ fn: (T) -> R)
            -> R

    Parameters

    fn

    A 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 operation is an escaping function depends upon the underlying lock mechanism. Because it may escape in some implementations, it has to be declared @escaping here to cover all cases.

    Declaration

    Swift

    open func write<R>(_ fn: (inout T) -> R)
            -> R

    Parameters

    operation

    A function that will be executed with the write lock held. The protected resource is passed as an inout parameter to operation so that it may be mutated.

    Return Value

    The result of calling fn().