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
34 changes: 28 additions & 6 deletions Sources/AsyncQueue/ActorQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,20 @@ extension Task {
operation: @MainActor @escaping () async -> Success,
) where Failure == Never {
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
return await executeOnMainActor(operation, endingTurn: turn)
let taskPriority = actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)
if turn.wasCurrentWhenReserved {
// The task's turn begins without waiting, so start the task on the main actor rather than hop there.
self.init(name: name, priority: taskPriority) { @MainActor in
await turn.begin()
return await executeOnMainActor(operation, endingTurn: turn)
}
} else {
// A task that waits for its turn resumes on the global concurrent executor whichever executor it waits on,
// so wait there rather than take an extra turn on the main actor.
self.init(name: name, priority: taskPriority) {
await turn.begin()
return await executeOnMainActor(operation, endingTurn: turn)
}
}
turn.register(self)
}
Expand Down Expand Up @@ -297,9 +308,20 @@ extension Task {
operation: @escaping @MainActor () async throws -> Success,
) where Failure == any Error {
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
return try await executeOnMainActor(operation, endingTurn: turn)
let taskPriority = actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)
if turn.wasCurrentWhenReserved {
// The task's turn begins without waiting, so start the task on the main actor rather than hop there.
self.init(name: name, priority: taskPriority) { @MainActor in
await turn.begin()
return try await executeOnMainActor(operation, endingTurn: turn)
}
} else {
// A task that waits for its turn resumes on the global concurrent executor whichever executor it waits on,
// so wait there rather than take an extra turn on the main actor.
self.init(name: name, priority: taskPriority) {
await turn.begin()
return try await executeOnMainActor(operation, endingTurn: turn)
}
}
turn.register(self)
}
Expand Down
44 changes: 32 additions & 12 deletions Sources/AsyncQueue/CancellableQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -376,12 +376,22 @@ extension Task {
@_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success,
) where Failure == Never {
self = fifoQueue.trackTask(performing: operation) { identifier, operation in
Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: {
defer {
fifoQueue.taskDidFinish(withIdentifier: identifier)
}
return await operation()
})
if isolation(of: operation) === MainActor.shared {
// Isolate this wrapper to the main actor too, so that the underlying queue can start and end the task there.
Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: { @MainActor in
defer {
fifoQueue.taskDidFinish(withIdentifier: identifier)
}
return await operation()
})
} else {
Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: {
defer {
fifoQueue.taskDidFinish(withIdentifier: identifier)
}
return await operation()
})
}
}
}

Expand Down Expand Up @@ -425,12 +435,22 @@ extension Task {
@_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success,
) where Failure == any Error {
self = fifoQueue.trackTask(performing: operation) { identifier, operation in
Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: {
defer {
fifoQueue.taskDidFinish(withIdentifier: identifier)
}
return try await operation()
})
if isolation(of: operation) === MainActor.shared {
// Isolate this wrapper to the main actor too, so that the underlying queue can start and end the task there.
Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: { @MainActor in
defer {
fifoQueue.taskDidFinish(withIdentifier: identifier)
}
return try await operation()
})
} else {
Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: {
defer {
fifoQueue.taskDidFinish(withIdentifier: identifier)
}
return try await operation()
})
}
}
}

Expand Down
117 changes: 108 additions & 9 deletions Sources/AsyncQueue/FIFOQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,17 @@ public final class FIFOQueue: Sendable {
/// or, if you pass `nil` there too, at the priority of the code that enqueues it.
public init(priority: TaskPriority? = nil) {
minimumPriority = MinimumPriority(priority)
turns = Turns()
}

#if DEBUG
/// Creates a FIFO queue that hands out turns from `turns`. Used by tests.
init(turns: Turns) {
minimumPriority = MinimumPriority(nil)
self.turns = turns
}
#endif

// MARK: Public

/// Whether every task you enqueued on this queue has finished.
Expand Down Expand Up @@ -85,7 +94,7 @@ public final class FIFOQueue: Sendable {
// MARK: Internal

/// Hands out turns to execute, in the order in which tasks are enqueued.
let turns = Turns()
let turns: Turns

/// The priority that the queue gives each of its tasks at least.
let minimumPriority: MinimumPriority
Expand Down Expand Up @@ -131,10 +140,31 @@ extension Task {
@_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success,
) where Failure == Never {
let turn = fifoQueue.turns.reserve()
self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
defer { turn.end() }
return await operation()
let taskPriority = fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)
if isolation(of: operation) === MainActor.shared {
let operation = UncheckedSendable(operation)
if turn.wasCurrentWhenReserved {
// The task's turn begins without waiting, so start the task on the main actor rather than hop there.
self.init(name: name, priority: taskPriority) { @MainActor in
await turn.begin()
return await executeOnMainActor(operation, endingTurn: turn)
}
} else {
// A task that waits for its turn resumes on the global concurrent executor whichever executor it waits on,
// so wait there rather than take an extra turn on the main actor.
self.init(name: name, priority: taskPriority) {
await turn.begin()
return await executeOnMainActor(operation, endingTurn: turn)
}
}
} else {
// A task can switch from the global concurrent executor to an idle actor, and back, without enqueuing a job,
// so a task whose operation is isolated to any other actor gains nothing from starting or ending there.
self.init(name: name, priority: taskPriority) {
await turn.begin()
defer { turn.end() }
return await operation()
}
}
turn.register(self)
}
Expand Down Expand Up @@ -178,10 +208,31 @@ extension Task {
@_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success,
) where Failure == any Error {
let turn = fifoQueue.turns.reserve()
self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
defer { turn.end() }
return try await operation()
let taskPriority = fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)
if isolation(of: operation) === MainActor.shared {
let operation = UncheckedSendable(operation)
if turn.wasCurrentWhenReserved {
// The task's turn begins without waiting, so start the task on the main actor rather than hop there.
self.init(name: name, priority: taskPriority) { @MainActor in
await turn.begin()
return try await executeOnMainActor(operation, endingTurn: turn)
}
} else {
// A task that waits for its turn resumes on the global concurrent executor whichever executor it waits on,
// so wait there rather than take an extra turn on the main actor.
self.init(name: name, priority: taskPriority) {
await turn.begin()
return try await executeOnMainActor(operation, endingTurn: turn)
}
}
} else {
// A task can switch from the global concurrent executor to an idle actor, and back, without enqueuing a job,
// so a task whose operation is isolated to any other actor gains nothing from starting or ending there.
self.init(name: name, priority: taskPriority) {
await turn.begin()
defer { turn.end() }
return try await operation()
}
}
turn.register(self)
}
Expand Down Expand Up @@ -284,3 +335,51 @@ extension Task {
turn.register(self)
}
}

// MARK: - Execution

/// The isolation of `operation`.
///
/// Reading `isolation` directly from a `sending` parameter of an initializer in an extension of `Task` crashes the
/// Swift 6.4 compiler, so the initializers read it through this function.
func isolation(of operation: @isolated(any) () async throws -> some Any) -> (any Actor)? {
operation.isolation
}

/// Executes `operation`, which is isolated to the main actor, and ends `turn` on the main actor once `operation` returns.
///
/// Ending the turn on the main actor keeps the task from hopping off of the main actor before it ends its turn.
@MainActor
private func executeOnMainActor<Success: Sendable>(
_ operation: UncheckedSendable<@isolated(any) () async -> Success>,
endingTurn turn: Turn,
) async -> Success {
defer { turn.end() }
return await operation.value()
}

/// Executes `operation`, which is isolated to the main actor, and ends `turn` on the main actor once `operation` returns
/// or throws.
///
/// Ending the turn on the main actor keeps the task from hopping off of the main actor before it ends its turn.
@MainActor
private func executeOnMainActor<Success: Sendable>(
_ operation: UncheckedSendable<@isolated(any) () async throws -> Success>,
endingTurn turn: Turn,
) async throws -> Success {
defer { turn.end() }
return try await operation.value()
}

/// Carries the operation that was sent to a queue's task into that task, and from there to the main actor.
///
/// A `sending` operation belongs to its own isolation region, which the task's operation takes over. The compiler cannot
/// see that a task's operation, which runs only once, gives the operation up when it passes it to the main actor,
/// so this box asserts it.
struct UncheckedSendable<Value>: @unchecked Sendable {
init(_ value: consuming Value) {
self.value = value
}

let value: Value
}
47 changes: 40 additions & 7 deletions Sources/AsyncQueue/Utilities/Turns.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,25 +38,41 @@ final class Turns: Sendable {
/// Tests pass `false` to exercise the behavior of runtimes that cannot escalate another task.
init(escalatesPriority: Bool = true) {
self.escalatesPriority = escalatesPriority
#if DEBUG
didEndTurn = nil
#endif
}

#if DEBUG
/// Creates turns that call `didEndTurn` each time a turn ends, from the code that ends it.
///
/// Tests use this to check where a queue's task ends its turn. This initializer exists only in debug builds,
/// so release builds pay nothing for it.
/// - Parameter didEndTurn: Called each time a turn ends, after the turn has ended.
init(didEndTurn: @escaping @Sendable () -> Void) {
escalatesPriority = true
self.didEndTurn = didEndTurn
}
#endif

// MARK: Internal

/// Reserves the next turn.
func reserve() -> Turn {
let ticket = Ticket()
let previousTicket = state.withLock { state in
let (previousTicket, isCurrent) = state.withLock { state -> (Ticket?, Bool) in
defer { state.lastTicket = ticket }
if let lastTicket = state.lastTicket, !lastTicket.hasEnded {
lastTicket.next = ticket
return (lastTicket, false)
} else {
// Every earlier turn has ended, so this turn is the current turn.
state.holder = ticket
state.holderPriority = nil
return (state.lastTicket, true)
}
return state.lastTicket
}
return Turn(turns: self, previousTicket: previousTicket, ticket: ticket)
return Turn(turns: self, previousTicket: previousTicket, ticket: ticket, wasCurrentWhenReserved: isCurrent)
}

/// Whether every turn reserved so far has ended.
Expand Down Expand Up @@ -107,6 +123,10 @@ final class Turns: Sendable {

fileprivate let escalatesPriority: Bool

#if DEBUG
private let didEndTurn: (@Sendable () -> Void)?
#endif

fileprivate func register(
escalation escalate: @escaping @Sendable (TaskPriority) -> Void,
for ticket: Ticket,
Expand All @@ -125,7 +145,7 @@ final class Turns: Sendable {
}
}

fileprivate func begin(_ ticket: Ticket, after previousTicket: Ticket?) async {
nonisolated(nonsending) fileprivate func begin(_ ticket: Ticket, after previousTicket: Ticket?) async {
if let previousTicket {
if escalatesPriority, #available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) {
await withTaskPriorityEscalationHandler {
Expand Down Expand Up @@ -167,6 +187,9 @@ final class Turns: Sendable {
// Escalating before resuming means the next task is scheduled at its escalated priority.
escalateNextHolder?()
successor?.resume()
#if DEBUG
didEndTurn?()
#endif
}

// MARK: Private
Expand Down Expand Up @@ -207,7 +230,7 @@ final class Turns: Sendable {

private let state = Mutex(State())

private func wait(for previousTicket: Ticket, as ticket: Ticket, recordingPriority: Bool) async {
nonisolated(nonsending) private func wait(for previousTicket: Ticket, as ticket: Ticket, recordingPriority: Bool) async {
await withUnsafeContinuation { (continuation: UnsafeContinuation<Void, Never>) in
let (hasPreviousTicketEnded, escalateHolder) = state.withLock { state -> (Bool, (@Sendable () -> Void)?) in
guard !previousTicket.hasEnded else { return (true, nil) }
Expand All @@ -234,14 +257,22 @@ final class Turns: Sendable {
struct Turn: Sendable {
// MARK: Initialization

fileprivate init(turns: Turns, previousTicket: Ticket?, ticket: Ticket) {
fileprivate init(turns: Turns, previousTicket: Ticket?, ticket: Ticket, wasCurrentWhenReserved: Bool) {
self.turns = turns
self.previousTicket = previousTicket
self.ticket = ticket
self.wasCurrentWhenReserved = wasCurrentWhenReserved
}

// MARK: Internal

/// Whether every earlier turn had ended when this turn was reserved, so that `begin()` returns without suspending.
///
/// A queue starts a task on the main actor only if the task's turn was current when it was reserved. A task that waits
/// for its turn resumes on the global concurrent executor whichever executor it waited on, so waiting on the main actor
/// would only make the task take an extra turn there.
let wasCurrentWhenReserved: Bool

/// The state of this turn. Used by tests.
let ticket: Ticket

Expand All @@ -252,8 +283,10 @@ struct Turn: Sendable {
}

/// Suspends until every earlier turn has ended.
///
/// Runs on the caller's executor, so a task on the main actor whose turn is current begins it without hopping off of the main actor.
/// - Warning: Must be called at most once, from the task that takes this turn.
func begin() async {
nonisolated(nonsending) func begin() async {
await turns.begin(ticket, after: previousTicket)
}

Expand Down
Loading
Loading