mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
Maybe we'll be able to plug in the standard one eventually: https://forums.swift.org/t/pitch-synchronous-mutual-exclusion-lock/69889
46 lines
974 B
Swift
46 lines
974 B
Swift
import Foundation
|
|
|
|
/// A Mutex protects a value with an NSLock.
|
|
final class Mutex<T> {
|
|
private var _value: T
|
|
private var lock = NSLock()
|
|
|
|
var value: T {
|
|
get { withLock { $0 } }
|
|
set { withLock { $0 = newValue } }
|
|
}
|
|
|
|
init(_ value: T) {
|
|
_value = value
|
|
}
|
|
|
|
/// Runs the provided closure while holding a lock on the value.
|
|
///
|
|
/// - parameter body: A closure that can modify the value.
|
|
func withLock<U>(_ body: (inout T) throws -> U) rethrows -> U {
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
return try body(&_value)
|
|
}
|
|
}
|
|
|
|
extension Mutex where T: Numeric {
|
|
@discardableResult
|
|
func increment() -> T {
|
|
withLock { n in
|
|
n += 1
|
|
return n
|
|
}
|
|
}
|
|
|
|
@discardableResult
|
|
func decrement() -> T {
|
|
withLock { n in
|
|
n -= 1
|
|
return n
|
|
}
|
|
}
|
|
}
|
|
|
|
extension Mutex: @unchecked Sendable where T: Sendable { }
|