Mutex
A synchronization primitive that protects shared mutable state via mutual exclusion.
Declaration
@frozen struct Mutex<Value> where Value : ~CopyableOverview
The Mutex type offers non-recursive exclusive access to the state it is protecting by blocking threads attempting to acquire the lock. Only one execution context at a time has access to the value stored within the Mutex allowing for exclusive access.
An example use of Mutex in a class used simultaneously by many threads protecting a Dictionary value:
class Manager {
let cache = Mutex<[Key: Resource]>([:])
func saveResource(_ resource: Resource, as key: Key) {
cache.withLock {
$0[key] = resource
}
}
}