diff --git a/GRDB/Utils/Mutex.swift b/GRDB/Utils/Mutex.swift index 43f93c226..da5c04702 100644 --- a/GRDB/Utils/Mutex.swift +++ b/GRDB/Utils/Mutex.swift @@ -49,3 +49,32 @@ extension Mutex where T: Numeric { } extension Mutex: @unchecked Sendable where T: Sendable { } + +// MARK: - UnsafeSendableMutex + +/// `UnsafeSendableMutex` is a Mutex that is always Sendable. It is unsafe, +/// because it does not guarantee that its value won't escape from the +/// critical section. +/// +/// We'll replace it with the SE-0433 Mutex when it is available. +/// +/// +/// For a longer discussion about Sendable and mutexes, see +/// +final class UnsafeSendableMutex: @unchecked Sendable { + private var _value: T + private var lock = NSLock() + + 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(_ body: (inout T) throws -> U) rethrows -> U { + lock.lock() + defer { lock.unlock() } + return try body(&_value) + } +} diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 517246707..93f4cc2dc 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -234,7 +234,9 @@ extension ValueObservation: Refinable { to stream: TextOutputStream? = nil) -> ValueObservation> { - let streamMutex = Mutex(stream ?? PrintOutputStream()) + // Safe because we don't escape the stream from the mutex + let streamMutex = UnsafeSendableMutex(stream ?? PrintOutputStream()) + let prefix = prefix.isEmpty ? "" : "\(prefix): " return handleEvents( willStart: {