Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 7 additions & 40 deletions Sources/AsyncQueue/CancellableQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -66,15 +64,15 @@ public final class CancellableQueue<UnderlyingQueue: Sendable>: 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
Expand All @@ -84,7 +82,7 @@ public final class CancellableQueue<UnderlyingQueue: Sendable>: Sendable {

/// Removes the identifier of a task that has finished executing.
func taskDidFinish(withIdentifier identifier: UUID) {
taskIdentifierToCancelMap.writeAsync {
taskIdentifierToCancelMap.withLock {
$0[identifier] = nil
}
}
Expand All @@ -93,7 +91,8 @@ public final class CancellableQueue<UnderlyingQueue: Sendable>: 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 {
Expand Down Expand Up @@ -399,35 +398,3 @@ extension Task {
fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel)
}
}

// MARK: - Lock

private final class Lock<State>: @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<R: Sendable>(_ 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())
}
36 changes: 3 additions & 33 deletions Sources/AsyncQueue/Utilities/Delivery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Success: Sendable, Failure: Error> {
func sendValue(_ value: Success) {
Expand Down Expand Up @@ -83,7 +83,8 @@ actor Delivery<Success: Sendable, Failure: Error> {
}

private var valueContinuations: [UnsafeContinuation<Success, Failure>] = []
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<Void, Never>?
Expand Down Expand Up @@ -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<State>: @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<R>(_ 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())
}
}
21 changes: 4 additions & 17 deletions Tests/AsyncQueueTests/CancellableQueueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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()
Expand All @@ -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()
Expand All @@ -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()
Expand All @@ -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()
Expand Down
Loading