CriticalSection

public struct CriticalSection

CriticalSections can be used to ensure exclusive access to a given resource.

By protecting a resource with a CriticalSection, you ensure that only one one thread can be executing code using that critical section at any given time.

CriticalSections are re-entrant, meaning that code already holding access to the critical section may re-enter the critical section without causing a deadlock. (The NSRecursiveLock class is used under the hood.)

  • Initializer.

    Declaration

    Swift

    public init()
  • Attempts to acquire exclusive access to the critical section before executing the passed-in function. The calling thread will block indefinitely until it is able to acquire the critical section.

    Declaration

    Swift

    public func execute<T>(_ fn: () -> T)
            -> T

    Parameters

    fn

    The function to execute once exclusive access to the critical section has been acquired.

  • Attempts to acquire exclusive access to the critical section before executing the passed-in function. The calling thread will block for at most timeout seconds while waiting to enter the critical section before giving up.

    Declaration

    Swift

    public func execute(timeout: TimeInterval, _ fn: () -> Void)
            -> Bool

    Parameters

    timeout

    The maximum time to wait while attempting to acquire exclusive access to the critical section.

    fn

    The function to execute once exclusive access to the critical section has been acquired.

    Return Value

    true if exclusive access to the critical section was acquired and fn was executed. false if timeout expired and fn was not executed.