mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-25 04:07:47 +00:00
... and make it conditionally Sendable, and it is no longer a property wrapper. It is conditionally Sendable because we can't use the techniques of the future standard Mutex (SE-0433 Synchronous Mutual Exclusion Lock, https://github.com/apple/swift-evolution/blob/main/proposals/0433-mutex.md). It is no longer a property wrapper because the Swift compiler can perform strict concurrency checks through a `var` property.
56 lines
1.4 KiB
Swift
56 lines
1.4 KiB
Swift
import Dispatch
|
|
|
|
/// A ReadWriteLock grants multiple readers and single-writer guarantees on a
|
|
/// value. It is backed by a concurrent DispatchQueue.
|
|
final class ReadWriteLock<T> {
|
|
private var _value: T
|
|
private var queue: DispatchQueue
|
|
|
|
var value: T {
|
|
get { read { $0 } }
|
|
set { withLock { $0 = newValue } }
|
|
}
|
|
|
|
init(_ value: T) {
|
|
_value = value
|
|
queue = DispatchQueue(label: "GRDB.ReadWriteLock", attributes: [.concurrent])
|
|
}
|
|
|
|
/// Reads the value.
|
|
func read<U>(_ body: (T) throws -> U) rethrows -> U {
|
|
try queue.sync {
|
|
try body(_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 {
|
|
try queue.sync(flags: [.barrier]) {
|
|
try body(&_value)
|
|
}
|
|
}
|
|
}
|
|
|
|
// @unchecked because `_wrappedValue` is protected by `queue`
|
|
extension ReadWriteLock: @unchecked Sendable where T: Sendable { }
|
|
|
|
extension ReadWriteLock 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
|
|
}
|
|
}
|
|
}
|