CriticalSection
public struct CriticalSection
CriticalSection
s 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.
CriticalSection
s 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 andfn
was executed.false
iftimeout
expired andfn
was not executed.