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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ Your operation sees the [task-local values](https://developer.apple.com/document
### Priority

- A task runs at the priority you pass to `Task(on:)`. If you pass `nil`, it runs at the priority of the code that enqueues it, as with `Task.init`.
- `FIFOQueue(priority:)` gives each of the queue's tasks at least that priority. A task that would run at a lower priority runs at the queue's priority instead.
- `FIFOQueue(priority:)` and `ActorQueue(priority:)` give each of the queue's tasks at least that priority. A task that would run at a lower priority runs at the queue's priority instead. `MainActor.queue` has no priority of its own.
- When a higher-priority task awaits a task's value, Swift raises, or *escalates*, that task's priority, as it does for any task.
- On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, a task that waits in a queue also raises the priority of the tasks ahead of it to its own priority. That way, the tasks ahead of a high-priority task don't run at a lower priority while it waits. On earlier releases, the tasks ahead keep their own priority.
- A task keeps a raised priority until it finishes.
Expand Down
27 changes: 22 additions & 5 deletions Sources/AsyncQueue/ActorQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,13 @@ public final class ActorQueue<ActorType: Actor>: @unchecked Sendable {
// MARK: Initialization

/// Creates an actor queue.
public init() {}
/// - Parameter priority: The lowest priority at which the queue's tasks run.
/// A task that would run at a lower priority runs at this priority instead.
/// Pass `nil` to run each task at the priority you pass to `Task(on:)`,
/// or, if you pass `nil` there too, at the priority of the code that enqueues it.
public init(priority: TaskPriority? = nil) {
minimumPriority = MinimumPriority(priority)
}

// MARK: Public

Expand Down Expand Up @@ -90,6 +96,9 @@ public final class ActorQueue<ActorType: Actor>: @unchecked Sendable {
/// Hands out turns to begin executing on the adopted actor, in the order in which tasks are enqueued.
let turns = Turns()

/// The priority that the queue gives each of its tasks at least.
let minimumPriority: MinimumPriority

// MARK: Fileprivate

/// The actor on whose isolated context our tasks run, force-unwrapped.
Expand Down Expand Up @@ -140,6 +149,7 @@ extension Task {
/// - priority: The priority of the task.
/// Pass `nil` to inherit the priority of the code that enqueues the task,
/// as a task created with `Task.init(name:priority:operation:)` does.
/// If the queue was created with a higher priority, the task runs at the queue's priority instead.
/// - actorQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
Expand All @@ -151,7 +161,7 @@ extension Task {
) where Failure == Never {
let executionContext = actorQueue.executionContext
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: priority) {
self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
return await execute(operation, on: executionContext, endingTurn: turn)
}
Expand Down Expand Up @@ -185,6 +195,7 @@ extension Task {
/// - priority: The priority of the task.
/// Pass `nil` to inherit the priority of the code that enqueues the task,
/// as a task created with `Task.init(name:priority:operation:)` does.
/// If the queue was created with a higher priority, the task runs at the queue's priority instead.
/// - actorQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
Expand All @@ -196,7 +207,7 @@ extension Task {
) where Failure == any Error {
let executionContext = actorQueue.executionContext
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: priority) {
self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
return try await execute(operation, on: executionContext, endingTurn: turn)
}
Expand Down Expand Up @@ -230,6 +241,7 @@ extension Task {
/// - priority: The priority of the task.
/// Pass `nil` to inherit the priority of the code that enqueues the task,
/// as a task created with `Task.init(name:priority:operation:)` does.
/// If the queue was created with a higher priority, the task runs at the queue's priority instead.
/// - actorQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
Expand All @@ -240,7 +252,7 @@ extension Task {
operation: @MainActor @escaping () async -> Success,
) where Failure == Never {
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: priority) {
self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
return await executeOnMainActor(operation, endingTurn: turn)
}
Expand Down Expand Up @@ -274,6 +286,7 @@ extension Task {
/// - priority: The priority of the task.
/// Pass `nil` to inherit the priority of the code that enqueues the task,
/// as a task created with `Task.init(name:priority:operation:)` does.
/// If the queue was created with a higher priority, the task runs at the queue's priority instead.
/// - actorQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
Expand All @@ -284,7 +297,7 @@ extension Task {
operation: @escaping @MainActor () async throws -> Success,
) where Failure == any Error {
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: priority) {
self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
return try await executeOnMainActor(operation, endingTurn: turn)
}
Expand Down Expand Up @@ -322,6 +335,10 @@ private func executeOnMainActor<Success>(

extension MainActor {
/// A global instance of an `ActorQueue<MainActor>`.
///
/// This queue has no priority of its own: each task runs at the priority you pass to `Task(on:)`,
/// or, if you pass `nil`, at the priority of the code that enqueues it.
/// Pass a `priority` to `Task(on:)` when you enqueue important work from low-priority code.
public static var queue: ActorQueue<MainActor> {
mainActorQueue
}
Expand Down
4 changes: 4 additions & 0 deletions Sources/AsyncQueue/CancellableQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ extension Task {
/// - priority: The priority of the task.
/// Pass `nil` to inherit the priority of the code that enqueues the task,
/// as a task created with `Task.init(name:priority:operation:)` does.
/// If the queue was created with a higher priority, the task runs at the queue's priority instead.
/// - actorQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
Expand Down Expand Up @@ -219,6 +220,7 @@ extension Task {
/// - priority: The priority of the task.
/// Pass `nil` to inherit the priority of the code that enqueues the task,
/// as a task created with `Task.init(name:priority:operation:)` does.
/// If the queue was created with a higher priority, the task runs at the queue's priority instead.
/// - actorQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
Expand Down Expand Up @@ -266,6 +268,7 @@ extension Task {
/// - priority: The priority of the task.
/// Pass `nil` to inherit the priority of the code that enqueues the task,
/// as a task created with `Task.init(name:priority:operation:)` does.
/// If the queue was created with a higher priority, the task runs at the queue's priority instead.
/// - actorQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
Expand Down Expand Up @@ -313,6 +316,7 @@ extension Task {
/// - priority: The priority of the task.
/// Pass `nil` to inherit the priority of the code that enqueues the task,
/// as a task created with `Task.init(name:priority:operation:)` does.
/// If the queue was created with a higher priority, the task runs at the queue's priority instead.
/// - actorQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
Expand Down
43 changes: 7 additions & 36 deletions Sources/AsyncQueue/FIFOQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public final class FIFOQueue: Sendable {
/// Pass `nil` to run each task at the priority you pass to `Task(on:)`,
/// or, if you pass `nil` there too, at the priority of the code that enqueues it.
public init(priority: TaskPriority? = nil) {
self.priority = priority
minimumPriority = MinimumPriority(priority)
}

// MARK: Public
Expand Down Expand Up @@ -87,37 +87,8 @@ public final class FIFOQueue: Sendable {
/// Hands out turns to execute, in the order in which tasks are enqueued.
let turns = Turns()

// MARK: Fileprivate

/// Returns the priority with which to create a task that was enqueued with the given priority.
/// - Parameter taskPriority: The priority with which the task was enqueued. `nil` means the priority of the enqueuing context.
fileprivate func priority(forTaskEnqueuedWith taskPriority: TaskPriority?) -> TaskPriority? {
if let priority, Self.priorityOfNewTask(enqueuedWith: taskPriority) < priority {
priority
} else {
// Keep the enqueued priority when it suffices, so that `Task` determines the task's priority itself.
taskPriority
}
}

/// Returns the priority that `Task.init(priority:)` gives a task created in the current context with the given priority.
private static func priorityOfNewTask(enqueuedWith taskPriority: TaskPriority?) -> TaskPriority {
// `Task` treats a priority with a raw value of zero as no priority.
if let taskPriority, taskPriority.rawValue != 0 {
return taskPriority
} else {
// Within a task, a new task inherits the task's base priority, not its escalated priority.
// Outside of a task, a new task takes the current thread's priority, or `.medium` if the thread has none.
let inheritedPriority = Task.basePriority ?? Task.currentPriority
guard inheritedPriority.rawValue != 0 else { return .medium }
// `Task` lowers an inherited user-interactive priority to user-initiated, which is `.high`.
return min(inheritedPriority, .high)
}
}

// MARK: Private

private let priority: TaskPriority?
/// The priority that the queue gives each of its tasks at least.
let minimumPriority: MinimumPriority
}

extension Task {
Expand Down Expand Up @@ -160,7 +131,7 @@ 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.priority(forTaskEnqueuedWith: priority)) {
self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
defer { turn.end() }
return await operation()
Expand Down Expand Up @@ -207,7 +178,7 @@ 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.priority(forTaskEnqueuedWith: priority)) {
self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
defer { turn.end() }
return try await operation()
Expand Down Expand Up @@ -256,7 +227,7 @@ extension Task {
operation: @Sendable @escaping (isolated ActorType) async -> Success,
) where Failure == Never {
let turn = fifoQueue.turns.reserve()
self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) {
self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
defer { turn.end() }
return await operation(isolatedActor)
Expand Down Expand Up @@ -305,7 +276,7 @@ extension Task {
operation: @Sendable @escaping (isolated ActorType) async throws -> Success,
) where Failure == any Error {
let turn = fifoQueue.turns.reserve()
self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) {
self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) {
await turn.begin()
defer { turn.end() }
return try await operation(isolatedActor)
Expand Down
64 changes: 64 additions & 0 deletions Sources/AsyncQueue/Utilities/MinimumPriority.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// MIT License
//
// Copyright (c) 2026 Dan Federman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

/// The priority that a queue gives each of its tasks at least.
struct MinimumPriority: Sendable {
// MARK: Initialization

/// - Parameter priority: The lowest priority at which the queue's tasks run.
/// Pass `nil` to run each task at the priority with which it was enqueued.
init(_ priority: TaskPriority?) {
self.priority = priority
}

// MARK: Internal

/// Returns the priority with which to create a task that was enqueued with the given priority.
/// - Parameter taskPriority: The priority with which the task was enqueued. `nil` means the priority of the enqueuing context.
func priority(forTaskEnqueuedWith taskPriority: TaskPriority?) -> TaskPriority? {
if let priority, Self.priorityOfNewTask(enqueuedWith: taskPriority) < priority {
priority
} else {
// Keep the enqueued priority when it suffices, so that `Task` determines the task's priority itself.
taskPriority
}
}

// MARK: Private

private let priority: TaskPriority?

/// Returns the priority that `Task.init(priority:)` gives a task created in the current context with the given priority.
private static func priorityOfNewTask(enqueuedWith taskPriority: TaskPriority?) -> TaskPriority {
// `Task` treats a priority with a raw value of zero as no priority.
if let taskPriority, taskPriority.rawValue != 0 {
return taskPriority
} else {
// Within a task, a new task inherits the task's base priority, not its escalated priority.
// Outside of a task, a new task takes the current thread's priority, or `.medium` if the thread has none.
let inheritedPriority = Task.basePriority ?? Task.currentPriority
guard inheritedPriority.rawValue != 0 else { return .medium }
// `Task` lowers an inherited user-interactive priority to user-initiated, which is `.high`.
return min(inheritedPriority, .high)
}
}
}
Loading
Loading