diff --git a/README.md b/README.md index c00ab17..bf5cea4 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,20 @@ [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fdfed%2Fswift-async-queue%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/dfed/swift-async-queue) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fdfed%2Fswift-async-queue%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/dfed/swift-async-queue) -A library of queues that enable sending ordered tasks from nonisolated to asynchronous contexts. +When you create several tasks from synchronous or `nonisolated` code, Swift doesn't guarantee the order in which they run, even if they all call the same actor. The queues in this library run tasks in the order you enqueue them. -## Task Ordering and Swift Concurrency +## Choosing a queue -Tasks sent from a nonisolated context to an asynchronous context in Swift Concurrency are inherently unordered. Consider the following test: +To enqueue a task, call `Task(on:)` with a queue instead of calling `Task.init`. The closure you pass is the task's *operation*: the code that the task runs. You can call `Task(on:)` from synchronous code. Like `Task.init`, it creates a new task and returns it, so you can wait for its value or cancel it. + +- Use a `FIFOQueue` when each task must finish before the next task starts. +- Use an `ActorQueue` when tasks must start in order on your own actor. The next task can start while an earlier one is suspended. +- Use `MainActor.queue` when tasks must start in order on the main actor. +- Use a `CancellableQueue` around a `FIFOQueue` or an `ActorQueue` when you need to cancel all of its tasks at once. + +## Running tasks in order + +Consider the following test: ```swift @Test @@ -38,15 +47,14 @@ func actorTaskOrdering() async { } ``` -Because the `Task` is spawned from a nonisolated execution context, the ordering of the scheduled asynchronous work is not guaranteed. +In the code above, the loop creates the tasks in order, but the tasks can run on the actor in a different order. When they do, the expectation fails. An [actor](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Actors) runs only one piece of code at a time, but it doesn't promise to run tasks in the order you create them. The sections below show how each queue runs tasks in the order you enqueue them. -While [actors](https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID645) are great at serializing tasks, there is no simple way in the standard Swift library to send ordered tasks to them from a nonisolated synchronous context, or from multiple execution contexts. +## Running tasks one at a time with `FIFOQueue` -### Executing asynchronous tasks in FIFO order +A `FIFOQueue` runs one task at a time, in the order you enqueue them: first in, first out. Each task waits until every task enqueued before it has finished. A task that is suspended at an `await` hasn't finished, so the next task keeps waiting. As a result, tasks start and finish in the order you enqueue them. -Use a `FIFOQueue` to execute asynchronous tasks enqueued from a nonisolated context in FIFO order. Tasks sent to one of these queues are guaranteed to begin _and end_ executing in the order in which they are enqueued. A `FIFOQueue` executes tasks in a similar manner to a `DispatchQueue`: enqueued tasks execute atomically, and the program will deadlock if a task executing on a `FIFOQueue` awaits results from the queue on which it is executing. +For example, here's how you might use a `FIFOQueue` so that the counter counts in order: -A `FIFOQueue` can easily execute asynchronous tasks from a nonisolated context in FIFO order: ```swift @Test func fIFOQueueOrdering() async { @@ -80,23 +88,35 @@ func fIFOQueueOrdering() async { } ``` -FIFO execution has a key downside: the queue must wait for all previously enqueued work – including suspended work – to complete before new work can begin. If you desire new work to start when a prior task suspends, utilize an `ActorQueue`. +In the code above, `incrementAndAssertCountEquals(_:)` is `nonisolated`, so synchronous code can call it. The operation runs with the same actor isolation as the code that enqueues it, like a task you create with `Task.init`. Here, that code is `nonisolated`, so the operation uses `await` to call the actor. + +Keep these points in mind when you use a `FIFOQueue`: + +- To run the operation on an actor, call `Task(on:isolatedTo:)` with that actor. The operation receives the actor, so it can use the actor's state without `await`. +- If the next task should start while one is suspended at an `await`, use an `ActorQueue`. +- Inside a task on a `FIFOQueue`, don't await another task that you enqueue on the same queue. The new task waits for the current task to finish, and the current task waits for the new one, so both wait forever. + +## Running tasks on your actor with `ActorQueue` -### Sending ordered asynchronous tasks to Actors from a nonisolated context +An `ActorQueue` runs tasks on your own actor, and the tasks start in the order you enqueue them. Once a task starts, it behaves like any other code on the actor: -Use an `ActorQueue` to send ordered asynchronous tasks to an `actor`'s isolated context from nonisolated or synchronous contexts. Tasks sent to an actor queue are guaranteed to begin executing in the order in which they are enqueued. However, unlike a `FIFOQueue`, execution order is guaranteed only until the first [suspension point](https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID639) within the enqueued task. An `ActorQueue` executes tasks within its adopted actor's isolated context, resulting in `ActorQueue` task execution having the same properties as `actor` code execution: code between suspension points is executed atomically, and tasks sent to a single `ActorQueue` can await results from the queue without deadlocking. +- When the task suspends at an `await`, the next task can start. +- Between [suspension points](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Defining-and-Calling-Asynchronous-Functions), the task runs without interruption from other code on the actor. +- A task can enqueue another task on the same queue and await its value. -An instance of an `ActorQueue` is designed to be utilized by a single `actor` instance: tasks sent to an `ActorQueue` utilize the isolated context of the queue‘s adopted `actor` to serialize tasks. As such, there are a couple requirements that must be met when dealing with an `ActorQueue`: -1. The lifecycle of any `ActorQueue` should not exceed the lifecycle of its `actor`. It is strongly recommended that an `ActorQueue` be a `private let` constant on the adopted `actor`. Enqueuing a task to an `ActorQueue` instance after its adopted `actor` has been deallocated will result in a crash. -2. An `actor` utilizing an `ActorQueue` should set the adopted execution context of the queue to `self` within the `actor`’s `init`. Failing to set an adopted execution context prior to enqueuing work on an `ActorQueue` will result in a crash. +Each `ActorQueue` belongs to one actor. To set one up: + +1. Store the queue in a `private let` property of the actor, so that the queue can't outlive the actor. Enqueuing a task after the actor is deallocated crashes. +2. In the actor's `init`, call `queue.adoptExecutionContext(of: self)` once. This tells the queue which actor to run its tasks on. Enqueuing a task before this call crashes. + +For example, here's the counter again, using an `ActorQueue`: -An `ActorQueue` can easily enqueue tasks that execute on an actor’s isolated context from a nonisolated context in order: ```swift @Test func actorQueueOrdering() async { actor Counter { init() { - // Adopting the execution context in `init` satisfies requirement #2 above. + // Calling `adoptExecutionContext(of:)` in `init` is step 2 above. queue.adoptExecutionContext(of: self) } @@ -109,7 +129,7 @@ func actorQueueOrdering() async { } private var count = 0 - // Making the queue a private let constant satisfies requirement #1 above. + // Storing the queue in a `private let` property is step 1 above. private let queue = ActorQueue() } @@ -125,11 +145,16 @@ func actorQueueOrdering() async { } ``` -### Sending ordered asynchronous tasks to the `@MainActor` from a nonisolated context +In the code above, the operation receives the actor as `myself`. The operation runs on the actor, so it reads and changes `count` without `await`. + +To wait for an operation's result, await the task's value. For example, a method of `Counter` could read the count with `let count = await Task(on: queue) { myself in myself.count }.value`. -Use `MainActor.queue` to send ordered asynchronous tasks to the `@MainActor`’s isolated context from nonisolated or synchronous contexts. Tasks sent to this queue type are guaranteed to begin executing in the order in which they are enqueued. The `MainActor.queue` is an `ActorQueue` that runs within the `@MainActor` global context: execution order is guaranteed only until the first [suspension point](https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID639) within the enqueued task. Similarly, code between suspension points is executed atomically, and tasks sent to the `MainActor.queue` can await results from the queue without deadlocking. +## Running tasks on the main actor with `MainActor.queue` + +`MainActor.queue` is an `ActorQueue` that runs tasks on the main actor. It's ready to use, with no setup. As with any `ActorQueue`, tasks start in the order you enqueue them, and when a task suspends at an `await`, the next task can start. + +For example, here's how you might enqueue tasks on the main actor from a `nonisolated` method: -A `MainActor.queue` can easily execute asynchronous tasks from a nonisolated context in FIFO order: ```swift @MainActor @Test @@ -164,11 +189,15 @@ func mainActorQueueOrdering() async { } ``` -### Cancelling all executing and pending tasks +In the code above, the operation runs on the main actor, so it uses `self` without `await`. + +## Cancelling tasks with `CancellableQueue` -Use a `CancellableQueue` to wrap a `FIFOQueue` or `ActorQueue` when you need the ability to cancel all currently executing and pending tasks at once. This is useful for scenarios like cancelling in-flight network requests when a view disappears, or abandoning a batch of operations when a user initiates a new action. +A `CancellableQueue` wraps a `FIFOQueue` or an `ActorQueue` and lets you cancel all of its tasks at once. For example, you might cancel a view's network requests when the view disappears, or cancel the work for a search when the user starts a new one. -A `CancellableQueue` wraps an underlying queue and tracks all tasks enqueued on it. Calling `cancelTasks()` will cancel both the currently executing task and any tasks waiting in the queue. Tasks that have already completed are unaffected, and tasks enqueued after `cancelTasks()` is called will execute normally. +- Calling `cancelTasks()` cancels every unfinished task that you enqueued on the `CancellableQueue`, whether it's running or waiting. +- Tasks that already finished aren't affected. Tasks you enqueue afterward run as usual. +- [Cancellation](#cancellation) is cooperative, so the operation should check for cancellation, as `loadImage(from:)` does below. ```swift @Test @@ -181,17 +210,17 @@ func cancellableQueueExample() async { } nonisolated - func loadImage(from url: URL) -> Task { + func loadImage(from url: URL) -> Task { Task(on: cancellableQueue) { myself in guard let image = try await myself.fetchImage(from: url) else { return nil } try Task.checkCancellation() - return myself.processImage(image) + return await myself.processImage(image) } } nonisolated func cancelAllLoads() { - // Cancels the currently loading image and any queued load requests. + // Cancels the image that is loading and the loads that are waiting. cancellableQueue.cancelTasks() } @@ -213,7 +242,7 @@ func cancellableQueueExample() async { let task2 = loader.loadImage(from: URL(string: "https://example.com/2.png")!) let task3 = loader.loadImage(from: URL(string: "https://example.com/3.png")!) - // Cancel all pending and executing loads. + // Cancel every load that hasn't finished. loader.cancelAllLoads() // All tasks are now cancelled. @@ -223,16 +252,42 @@ func cancellableQueueExample() async { } ``` -A `CancellableQueue` can also wrap a `FIFOQueue` for FIFO-ordered cancellable tasks: +In the code above, each load calls `Task.checkCancellation()` after it fetches the image. A cancelled load throws `CancellationError` there, so it doesn't process the image. + +A `CancellableQueue` can also wrap a `FIFOQueue`: + ```swift let cancellableQueue = CancellableQueue(underlyingQueue: FIFOQueue()) Task(on: cancellableQueue) { - // This work can be cancelled via cancellableQueue.cancelTasks() + // Calling `cancellableQueue.cancelTasks()` cancels this task. await performWork() } ``` +## Task-local values, priority, and cancellation + +`Task(on:)` creates a new [unstructured task](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Unstructured-Concurrency), as `Task.init` does, and your operation runs in that task. So the task behaves like a task you create with `Task.init`. + +### Task-local values + +Your operation sees the [task-local values](https://developer.apple.com/documentation/swift/tasklocal) of the code that enqueues it, as with `Task.init`. + +### 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. +- When a higher-priority task awaits a task's value, Swift raises, or *escalates*, that task's priority, as it does for any task. + +### Cancellation + +Cancellation is [cooperative](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Task-Cancellation), as it is for any Swift task: + +- Calling a task's `cancel()` method, or calling `cancelTasks()` on the `CancellableQueue` you enqueued it on, marks the task as cancelled right away. +- The task keeps its place in the queue. Its operation still runs, in the same order as if you hadn't cancelled it. +- The operation decides how to respond. It can check `Task.isCancelled`, or call `Task.checkCancellation()` to throw a `CancellationError`. +- An operation that doesn't check for cancellation runs to completion, and the tasks behind it wait for it as usual. + ## Installation To install swift-async-queue in your project with [Swift Package Manager](https://github.com/apple/swift-package-manager), the following lines can be added to your `Package.swift` file: diff --git a/Sources/AsyncQueue/ActorQueue.swift b/Sources/AsyncQueue/ActorQueue.swift index 45322af..6359975 100644 --- a/Sources/AsyncQueue/ActorQueue.swift +++ b/Sources/AsyncQueue/ActorQueue.swift @@ -20,12 +20,12 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -/// A queue that enables enqueuing ordered asynchronous tasks from a nonisolated context onto an adopted actor's isolated context. -/// Tasks are guaranteed to begin executing in the order in which they are enqueued. However, if a task suspends it will allow subsequently enqueued tasks to begin executing. -/// This queue exhibits the execution behavior of an actor: tasks sent to this queue can re-enter the queue, and tasks may execute in non-FIFO order when a task suspends. +/// A queue that runs tasks on an actor and starts them in the order you enqueue them. +/// You can enqueue tasks from synchronous or `nonisolated` code. +/// Once a task starts, it behaves like any other code on the actor: when it suspends at an `await`, the next task can start, +/// and it can enqueue another task on the same queue and await its value. /// -/// An `ActorQueue` ensures tasks sent from a nonisolated context to a single actor's isolated context begin execution in order. -/// Here is an example of how an `ActorQueue` should be utilized within an actor: +/// Each `ActorQueue` belongs to one actor. Here is an example of how to use an `ActorQueue` within an actor: /// ```swift /// public actor LogStore { /// @@ -49,22 +49,22 @@ /// } /// ``` /// -/// - Warning: The `ActorQueue`'s conformance to `@unchecked Sendable` is safe if and only if `adoptExecutionContext(of:)` is called only from the adopted actor's `init` method. -/// - Precondition: The lifecycle of an `ActorQueue` must not exceed that of the adopted actor. +/// - Warning: The `ActorQueue`'s conformance to `@unchecked Sendable` is safe if and only if `adoptExecutionContext(of:)` is called only from the `init` method of the actor you pass to it. +/// - Precondition: An `ActorQueue` must not outlive the actor you pass to `adoptExecutionContext(of:)`. public final class ActorQueue: @unchecked Sendable { // MARK: Initialization - /// Instantiates an actor queue. + /// Creates an actor queue. public init() {} // MARK: Public - /// Sets the actor context within which each `enqueue` and `enqueueAndWait`ed task will execute. - /// It is recommended that this method be called in the adopted actor’s `init` method. - /// **Must be called prior to enqueuing any work on the receiver.** + /// Sets the actor on which this queue runs its tasks. + /// Call this method once, in that actor's `init`, before you enqueue any task on this queue. /// - /// - Parameter actor: The actor on which the queue's task will execute. This parameter is not retained by the receiver. - /// - Warning: Calling this method more than once will result in an assertion failure. + /// - Parameter actor: The actor on which this queue runs its tasks. + /// This queue doesn't retain the actor, but each enqueued task retains it until the task finishes. + /// - Warning: Calling this method more than once causes an assertion failure. public func adoptExecutionContext(of actor: ActorType) { assert(weakExecutionContext == nil) // Adopting multiple executionContexts on the same queue is API abuse. weakExecutionContext = actor @@ -99,29 +99,28 @@ public final class ActorQueue: @unchecked Sendable { extension Task { /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. + /// as part of a new unstructured task isolated to the queue's actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. - /// - priority: The priority of the operation 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. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -140,30 +139,28 @@ extension Task { } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. + /// as part of a new unstructured task isolated to the queue's actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -182,30 +179,28 @@ extension Task { } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. + /// as part of a new unstructured task isolated to the main actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -223,30 +218,28 @@ extension Task { } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. + /// as part of a new unstructured task isolated to the main actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult diff --git a/Sources/AsyncQueue/CancellableQueue.swift b/Sources/AsyncQueue/CancellableQueue.swift index b6be404..38b351b 100644 --- a/Sources/AsyncQueue/CancellableQueue.swift +++ b/Sources/AsyncQueue/CancellableQueue.swift @@ -27,23 +27,22 @@ #endif import Synchronization -/// A queue wrapper that enables cancelling all currently executing and pending tasks. -/// -/// A `CancellableQueue` wraps either a `FIFOQueue` or an `ActorQueue` and tracks all tasks enqueued on it. +/// A queue that wraps a `FIFOQueue` or an `ActorQueue` and lets you cancel all of its unfinished tasks at once. public final class CancellableQueue: Sendable { // MARK: Initialization - /// Instantiates a cancellable queue. - /// - Parameter underlyingQueue: The queue whose work can be cancelled. + /// Creates a cancellable queue. + /// - Parameter underlyingQueue: The `FIFOQueue` or `ActorQueue` to wrap. public init(underlyingQueue: UnderlyingQueue) { self.underlyingQueue = underlyingQueue } // MARK: Public - /// Cancels currently executing and pending tasks. Does not affect tasks enqueued after this method is called. + /// Cancels every unfinished task that you enqueued on this queue, whether it's running or waiting. + /// Tasks that you enqueue afterward aren't affected. /// - /// A task that another thread is still enqueuing when this method is called is cancelled as soon as its enqueuing completes. + /// If another thread is still enqueuing a task when you call this method, the task is cancelled as soon as it's enqueued. /// /// If another call to this method is in progress, this call may return before the other call finishes cancelling the tasks it found. public func cancelTasks() { @@ -146,24 +145,29 @@ public final class CancellableQueue: Sendable { extension Task { /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the queue's actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -184,24 +188,29 @@ extension Task { } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the queue's actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -222,24 +231,29 @@ extension Task { } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the main actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -260,24 +274,29 @@ extension Task { } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the main actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -298,32 +317,42 @@ extension Task { } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task that inherits the current isolated context. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task that runs with the same actor isolation as the code that enqueues it. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the 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. /// - fifoQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult public init( name: String? = nil, + priority: TaskPriority? = nil, on fifoQueue: CancellableQueue, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success, ) where Failure == Never { self = fifoQueue.trackTask(performing: operation) { identifier, operation in - Task(name: name, on: fifoQueue.underlyingQueue, operation: { + Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: { defer { fifoQueue.taskDidFinish(withIdentifier: identifier) } @@ -333,32 +362,42 @@ extension Task { } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task that inherits the current isolated context. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task that runs with the same actor isolation as the code that enqueues it. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the 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. /// - fifoQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult public init( name: String? = nil, + priority: TaskPriority? = nil, on fifoQueue: CancellableQueue, @_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, on: fifoQueue.underlyingQueue, operation: { + Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: { defer { fifoQueue.taskDidFinish(withIdentifier: identifier) } @@ -368,24 +407,31 @@ extension Task { } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task isolated to the given actor. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the given actor. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// 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. /// - fifoQueue: The queue on which to enqueue the task. /// - isolatedActor: The actor to which the operation is isolated. /// - operation: The operation to perform. @@ -408,24 +454,31 @@ extension Task { } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task isolated to the given actor. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the given actor. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// 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. /// - fifoQueue: The queue on which to enqueue the task. /// - isolatedActor: The actor to which the operation is isolated. /// - operation: The operation to perform. diff --git a/Sources/AsyncQueue/FIFOQueue.swift b/Sources/AsyncQueue/FIFOQueue.swift index b8ebc98..e8bc480 100644 --- a/Sources/AsyncQueue/FIFOQueue.swift +++ b/Sources/AsyncQueue/FIFOQueue.swift @@ -20,9 +20,12 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -/// A queue that executes asynchronous tasks enqueued from a nonisolated context in FIFO order. -/// Tasks are guaranteed to begin _and end_ executing in the order in which they are enqueued. -/// Asynchronous tasks sent to this queue work as they would in a `DispatchQueue` type. Attempting to `enqueueAndWait` this queue from a task executing on this queue will result in a deadlock. +/// A queue that runs one task at a time, in the order you enqueue them: first in, first out. +/// You can enqueue tasks from synchronous or `nonisolated` code. +/// Each task waits until every task enqueued before it has finished, so tasks start and finish in the order you enqueue them. +/// A task that is suspended at an `await` hasn't finished. +/// Inside a task on this queue, don't await another task that you enqueue on the same queue: +/// each task waits for the other, so both wait forever. public final class FIFOQueue: Sendable { // MARK: Initialization @@ -75,29 +78,30 @@ public final class FIFOQueue: Sendable { extension Task { /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task that inherits the current isolated context. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task that runs with the same actor isolation as the code that enqueues it. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the 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. /// - fifoQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -116,29 +120,30 @@ extension Task { } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task that inherits the current isolated context. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task that runs with the same actor isolation as the code that enqueues it. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the 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. /// - fifoQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -157,30 +162,30 @@ extension Task { } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task isolated to the given actor. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the given actor. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// 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. /// - fifoQueue: The queue on which to enqueue the task. /// - isolatedActor: The actor to which the operation is isolated. /// - operation: The operation to perform. @@ -201,30 +206,30 @@ extension Task { } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task isolated to the given actor. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the given actor. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// 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. /// - fifoQueue: The queue on which to enqueue the task. /// - isolatedActor: The actor to which the operation is isolated. /// - operation: The operation to perform. diff --git a/Tests/AsyncQueueTests/CancellableQueueTests.swift b/Tests/AsyncQueueTests/CancellableQueueTests.swift index cbf1a29..5fe84da 100644 --- a/Tests/AsyncQueueTests/CancellableQueueTests.swift +++ b/Tests/AsyncQueueTests/CancellableQueueTests.swift @@ -699,6 +699,20 @@ struct CancellableQueueTests { #expect(!task.isCancelled) } + @Test + func task_fifoQueue_withPriority_executesAtThatPriority() async { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.low, .low]) + } + @Test func task_seesCallersTaskLocalValues() async throws { let fifoQueue = CancellableQueue(underlyingQueue: FIFOQueue())