From 0958fc07084871af13cc1aab3b8a443c30daebe9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 22:13:12 +0000 Subject: [PATCH] Replace DispatchQueue-backed locks with Mutex Now that the platform minimums include the Synchronization module, use `Mutex` for the state that `Delivery` and `CancellableQueue` guard instead of hand-rolled locks built on serial dispatch queues. `CancellableQueue` also stops deferring its bookkeeping with `DispatchQueue.async`: reservations, registrations, and removals now apply synchronously, in program order. This is safe because no task is cancelled while the lock is held. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM --- Sources/AsyncQueue/CancellableQueue.swift | 47 +++---------------- Sources/AsyncQueue/Utilities/Delivery.swift | 36 ++------------ .../CancellableQueueTests.swift | 21 ++------- 3 files changed, 14 insertions(+), 90 deletions(-) diff --git a/Sources/AsyncQueue/CancellableQueue.swift b/Sources/AsyncQueue/CancellableQueue.swift index 23ca121..857ebb7 100644 --- a/Sources/AsyncQueue/CancellableQueue.swift +++ b/Sources/AsyncQueue/CancellableQueue.swift @@ -25,9 +25,7 @@ #else import Foundation #endif -#if canImport(Dispatch) - import Dispatch -#endif +import Synchronization /// A queue wrapper that enables cancelling all currently executing and pending tasks. /// @@ -66,15 +64,15 @@ public final class CancellableQueue: Sendable { /// Reserving before the task starts ensures the task's removal of the identifier can never be processed before the reservation. func reserveTaskIdentifier() -> UUID { let identifier = UUID() - taskIdentifierToCancelMap.writeAsync { - $0.updateValue(nil, forKey: identifier) + taskIdentifierToCancelMap.withLock { + _ = $0.updateValue(nil, forKey: identifier) } return identifier } /// Registers the `cancel` closure for a task whose identifier was previously reserved. func registerCancellation(forTaskWithIdentifier identifier: UUID, _ cancel: @escaping @Sendable () -> Void) { - taskIdentifierToCancelMap.writeAsync { + taskIdentifierToCancelMap.withLock { // Skip registration if the identifier was already removed because the task already finished. if $0.keys.contains(identifier) { $0[identifier] = cancel @@ -84,7 +82,7 @@ public final class CancellableQueue: Sendable { /// Removes the identifier of a task that has finished executing. func taskDidFinish(withIdentifier identifier: UUID) { - taskIdentifierToCancelMap.writeAsync { + taskIdentifierToCancelMap.withLock { $0[identifier] = nil } } @@ -93,7 +91,8 @@ public final class CancellableQueue: Sendable { fileprivate let underlyingQueue: UnderlyingQueue - fileprivate let taskIdentifierToCancelMap = Lock<[UUID: (@Sendable () -> Void)?]>(value: [:]) + /// Never cancel a task while holding this lock: cancellation handlers run synchronously and may call back into this queue. + fileprivate let taskIdentifierToCancelMap = Mutex<[UUID: (@Sendable () -> Void)?]>([:]) } extension Task { @@ -399,35 +398,3 @@ extension Task { fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) } } - -// MARK: - Lock - -private final class Lock: @unchecked Sendable { - // MARK: Initialization - - init(value: State) { - unsafeValue = value - } - - // MARK: Fileprivate - - /// Executes `body` while holding the lock. - /// - Warning: `body` must not cancel a task, resume a continuation, or otherwise call out to code that may re-enter this lock. - fileprivate func withLock(_ body: @Sendable (inout State) throws -> R) rethrows -> R { - try lockQueue.sync { - try body(&unsafeValue) - } - } - - fileprivate func writeAsync(_ body: @Sendable @escaping (inout State) -> Void) { - lockQueue.async { - body(&self.unsafeValue) - } - } - - // MARK: Private - - private var unsafeValue: State - - private let lockQueue = DispatchQueue(label: "ReadWriteLock.Queue", target: DispatchQueue.global()) -} diff --git a/Sources/AsyncQueue/Utilities/Delivery.swift b/Sources/AsyncQueue/Utilities/Delivery.swift index 23e050e..7a658eb 100644 --- a/Sources/AsyncQueue/Utilities/Delivery.swift +++ b/Sources/AsyncQueue/Utilities/Delivery.swift @@ -20,7 +20,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -import Dispatch +import Synchronization actor Delivery { func sendValue(_ value: Success) { @@ -83,7 +83,8 @@ actor Delivery { } private var valueContinuations: [UnsafeContinuation] = [] - private let taskContainer = Locked(value: TaskContainer()) + /// Never cancel a task while holding this lock: cancellation handlers run synchronously and may cancel other tasks. + private let taskContainer = Mutex(TaskContainer()) struct TaskContainer { var task: Task? @@ -116,34 +117,3 @@ extension Delivery where Failure == any Error { } } } - -// MARK: - Locked - -// We'd use `OSAllocatedUnfairLock` or `Mutex` but the minimum supported version is much higher than what we support. -private struct Locked: @unchecked Sendable { - init(value: State) { - container = .init(value: value) - } - - /// Executes `body` while holding the lock. - /// - Warning: `body` must not cancel a task, resume a continuation, or otherwise call out to code that may re-enter this lock. - func withLock(_ body: @Sendable (inout State) throws -> R) rethrows -> R where R: Sendable { - try container.lockQueue.sync { - var value = container.unsafeValue - let returnValue = try body(&value) - container.unsafeValue = value - return returnValue - } - } - - private let container: UnsafeContainer - - private final class UnsafeContainer: @unchecked Sendable { - init(value: State) { - unsafeValue = value - } - - var unsafeValue: State - let lockQueue = DispatchQueue(label: "Locked.lockQueue", target: DispatchQueue.global()) - } -} diff --git a/Tests/AsyncQueueTests/CancellableQueueTests.swift b/Tests/AsyncQueueTests/CancellableQueueTests.swift index 61991ac..7d0993b 100644 --- a/Tests/AsyncQueueTests/CancellableQueueTests.swift +++ b/Tests/AsyncQueueTests/CancellableQueueTests.swift @@ -147,9 +147,6 @@ struct CancellableQueueTests { // Wait for the task to end, so that its operation has run. try await task.value - // `cancelTasks()` returns only once the queue has processed every earlier registration, including the task's. - // The task has ended, so this call cancels nothing, and the task is cancelled only if registering it cancelled it. - systemUnderTest.cancelTasks() #expect(!task.isCancelled) } @@ -269,9 +266,6 @@ struct CancellableQueueTests { // Wait for the task to end, so that its operation has run. try await task.value - // `cancelTasks()` returns only once the queue has processed every earlier registration, including the task's. - // The task has ended, so this call cancels nothing, and the task is cancelled only if registering it cancelled it. - systemUnderTest.cancelTasks() #expect(!task.isCancelled) } @@ -381,9 +375,6 @@ struct CancellableQueueTests { // Wait for the task to end, so that its operation has run. try await task.value - // `cancelTasks()` returns only once the queue has processed every earlier registration, including the task's. - // The task has ended, so this call cancels nothing, and the task is cancelled only if registering it cancelled it. - systemUnderTest.cancelTasks() #expect(!task.isCancelled) } @@ -506,8 +497,7 @@ struct CancellableQueueTests { try doWork() } - // The task submits its cancellation's registration before `Task(on:)` returns, `cancelTasks()` processes every - // earlier submission before it cancels, and the task cannot end until it is allowed to. + // The task registers its cancellation before `Task(on:)` returns, and cannot end until it is allowed to. await taskStarted.wait() systemUnderTest.cancelTasks() await taskAllowedToEnd.signal() @@ -527,8 +517,7 @@ struct CancellableQueueTests { try doWork() } - // The task submits its cancellation's registration before `Task(on:)` returns, `cancelTasks()` processes every - // earlier submission before it cancels, and the task cannot end until it is allowed to. + // The task registers its cancellation before `Task(on:)` returns, and cannot end until it is allowed to. await taskStarted.wait() systemUnderTest.cancelTasks() await taskAllowedToEnd.signal() @@ -551,8 +540,7 @@ struct CancellableQueueTests { try doWork() } - // The task submits its cancellation's registration before `Task(on:)` returns, `cancelTasks()` processes every - // earlier submission before it cancels, and the task cannot end until it is allowed to. + // The task registers its cancellation before `Task(on:)` returns, and cannot end until it is allowed to. await taskStarted.wait() systemUnderTest.cancelTasks() await taskAllowedToEnd.signal() @@ -572,8 +560,7 @@ struct CancellableQueueTests { try doWork() } - // The task submits its cancellation's registration before `Task(on:)` returns, `cancelTasks()` processes every - // earlier submission before it cancels, and the task cannot end until it is allowed to. + // The task registers its cancellation before `Task(on:)` returns, and cannot end until it is allowed to. await taskStarted.wait() systemUnderTest.cancelTasks() await taskAllowedToEnd.signal()