diff --git a/Sources/AsyncQueue/ActorQueue.swift b/Sources/AsyncQueue/ActorQueue.swift index 0e5fc71..57ccb07 100644 --- a/Sources/AsyncQueue/ActorQueue.swift +++ b/Sources/AsyncQueue/ActorQueue.swift @@ -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) } @@ -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) } diff --git a/Sources/AsyncQueue/CancellableQueue.swift b/Sources/AsyncQueue/CancellableQueue.swift index b34f8d4..b317ab8 100644 --- a/Sources/AsyncQueue/CancellableQueue.swift +++ b/Sources/AsyncQueue/CancellableQueue.swift @@ -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() + }) + } } } @@ -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() + }) + } } } diff --git a/Sources/AsyncQueue/FIFOQueue.swift b/Sources/AsyncQueue/FIFOQueue.swift index 96acd4c..8159041 100644 --- a/Sources/AsyncQueue/FIFOQueue.swift +++ b/Sources/AsyncQueue/FIFOQueue.swift @@ -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. @@ -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 @@ -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) } @@ -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) } @@ -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( + _ 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( + _ 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: @unchecked Sendable { + init(_ value: consuming Value) { + self.value = value + } + + let value: Value +} diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index d538c94..3c5d439 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -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. @@ -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, @@ -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 { @@ -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 @@ -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) in let (hasPreviousTicketEnded, escalateHolder) = state.withLock { state -> (Bool, (@Sendable () -> Void)?) in guard !previousTicket.hasEnded else { return (true, nil) } @@ -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 @@ -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) } diff --git a/Tests/AsyncQueueTests/ActorQueueTests.swift b/Tests/AsyncQueueTests/ActorQueueTests.swift index 1aca871..54c397a 100644 --- a/Tests/AsyncQueueTests/ActorQueueTests.swift +++ b/Tests/AsyncQueueTests/ActorQueueTests.swift @@ -21,6 +21,7 @@ // SOFTWARE. import Foundation +import Synchronization import Testing @testable import AsyncQueue @@ -1055,6 +1056,70 @@ struct ActorQueueTests { #expect(priority.map { $0 >= .high } == true) } + @MainActor + @Test + func mainTask_whenTurnBeginsWithoutWaiting_startsOnMainActorWithoutHoppingThere() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: mainActorQueue) { + executionOrder.withLock { $0.append("queued") } + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @MainActor + @Test + func mainThrowingTask_whenTurnBeginsWithoutWaiting_startsOnMainActorWithoutHoppingThere() async throws { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: mainActorQueue) { + executionOrder.withLock { $0.append("queued") } + try doWork() + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + try await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @Test + func mainTask_whenTurnCannotBeginYet_beginsInOrderOnceTurnBegins() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + // Hold the turn before the tasks' turns, so that every task waits for its turn off of the main actor. + let heldTurn = mainActorQueue.turns.reserve() + await heldTurn.begin() + let executionOrder = Mutex([Int]()) + let tasks = (0..<100).map { index in + Task(on: mainActorQueue) { + executionOrder.withLock { $0.append(index) } + } + } + heldTurn.end() + for task in tasks { + await task.value + } + #expect(executionOrder.withLock(\.self) == Array(0..<100)) + } + // MARK: Private private let systemUnderTest: ActorQueue diff --git a/Tests/AsyncQueueTests/CancellableQueueTests.swift b/Tests/AsyncQueueTests/CancellableQueueTests.swift index db12c2a..bbedea2 100644 --- a/Tests/AsyncQueueTests/CancellableQueueTests.swift +++ b/Tests/AsyncQueueTests/CancellableQueueTests.swift @@ -21,6 +21,7 @@ // SOFTWARE. import Dispatch +import Foundation import Synchronization import Testing @@ -813,6 +814,76 @@ struct CancellableQueueTests { #expect(values == Array(repeating: "caller", count: 8)) } + @MainActor + @Test + func task_fifoQueue_withMainActorOperation_startsOnMainActorWithoutHoppingThere() async { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: systemUnderTest) { + executionOrder.withLock { $0.append("queued") } + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @MainActor + @Test + func throwingTask_fifoQueue_withMainActorOperation_startsOnMainActorWithoutHoppingThere() async throws { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: systemUnderTest) { + executionOrder.withLock { $0.append("queued") } + try doWork() + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + try await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + #if DEBUG + @Test + func task_fifoQueue_withMainActorOperation_endsItsTurnOnMainActor() async { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + let task = Task(on: CancellableQueue(underlyingQueue: FIFOQueue(turns: turns))) { @MainActor in + MainActor.assertIsolated() + } + await task.value + // A task that hopped off of the main actor before ending its turn would end it on another thread. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [true]) + } + + @Test + func throwingTask_fifoQueue_withMainActorOperation_endsItsTurnOnMainActor() async throws { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + let task = Task(on: CancellableQueue(underlyingQueue: FIFOQueue(turns: turns))) { @MainActor in + MainActor.assertIsolated() + try doWork() + } + try await task.value + // A task that hopped off of the main actor before ending its turn would end it on another thread. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [true]) + } + #endif + // MARK: Private private struct TestError: Error {} diff --git a/Tests/AsyncQueueTests/FIFOQueueTests.swift b/Tests/AsyncQueueTests/FIFOQueueTests.swift index a833c12..570681a 100644 --- a/Tests/AsyncQueueTests/FIFOQueueTests.swift +++ b/Tests/AsyncQueueTests/FIFOQueueTests.swift @@ -21,6 +21,7 @@ // SOFTWARE. import Foundation +import Synchronization import Testing @testable import AsyncQueue @@ -1037,6 +1038,150 @@ struct FIFOQueueTests { #expect(priority.map { $0 >= .high } == true) } + @MainActor + @Test + func task_withMainActorOperation_whenTurnBeginsWithoutWaiting_startsOnMainActorWithoutHoppingThere() async { + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: systemUnderTest) { + executionOrder.withLock { $0.append("queued") } + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @MainActor + @Test + func throwingTask_withMainActorOperation_whenTurnBeginsWithoutWaiting_startsOnMainActorWithoutHoppingThere() async throws { + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: systemUnderTest) { + executionOrder.withLock { $0.append("queued") } + try doWork() + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + try await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @Test + func task_withMainActorOperation_whenTurnCannotBeginYet_beginsInOrderOnceTurnBegins() async { + // Hold the turn before the tasks' turns, so that every task waits for its turn off of the main actor. + let heldTurn = systemUnderTest.turns.reserve() + await heldTurn.begin() + let executionOrder = Mutex([Int]()) + let tasks = (0..<100).map { index in + Task(on: systemUnderTest) { @MainActor in + executionOrder.withLock { $0.append(index) } + } + } + heldTurn.end() + for task in tasks { + await task.value + } + #expect(executionOrder.withLock(\.self) == Array(0..<100)) + } + + @Test + func throwingTask_withMainActorOperation_whenTurnCannotBeginYet_beginsInOrderOnceTurnBegins() async throws { + // Hold the turn before the tasks' turns, so that every task waits for its turn off of the main actor. + let heldTurn = systemUnderTest.turns.reserve() + await heldTurn.begin() + let executionOrder = Mutex([Int]()) + let tasks = (0..<100).map { index in + Task(on: systemUnderTest) { @MainActor in + executionOrder.withLock { $0.append(index) } + try doWork() + } + } + heldTurn.end() + for task in tasks { + try await task.value + } + #expect(executionOrder.withLock(\.self) == Array(0..<100)) + } + + #if DEBUG + @Test + func task_withMainActorOperation_whenTurnBeginsWithoutWaiting_endsItsTurnOnMainActor() async { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + let task = Task(on: FIFOQueue(turns: turns)) { @MainActor in + MainActor.assertIsolated() + } + await task.value + // A task that hopped off of the main actor before ending its turn would end it on another thread. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [true]) + } + + @Test + func throwingTask_withMainActorOperation_whenTurnBeginsWithoutWaiting_endsItsTurnOnMainActor() async throws { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + let task = Task(on: FIFOQueue(turns: turns)) { @MainActor in + MainActor.assertIsolated() + try doWork() + } + try await task.value + // A task that hopped off of the main actor before ending its turn would end it on another thread. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [true]) + } + + @Test + func task_withMainActorOperation_whenTurnCannotBeginYet_endsItsTurnOnMainActor() async { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + // Hold the turn before the task's turn, so that the task waits for its turn off of the main actor. + let heldTurn = turns.reserve() + await heldTurn.begin() + let task = Task(on: FIFOQueue(turns: turns)) { @MainActor in + MainActor.assertIsolated() + } + heldTurn.end() + await task.value + // The test ends the held turn off of the main actor. A task that hopped off of the main actor before ending its turn + // would end it on another thread too. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [false, true]) + } + + @Test + func throwingTask_withMainActorOperation_whenTurnCannotBeginYet_endsItsTurnOnMainActor() async throws { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + // Hold the turn before the task's turn, so that the task waits for its turn off of the main actor. + let heldTurn = turns.reserve() + await heldTurn.begin() + let task = Task(on: FIFOQueue(turns: turns)) { @MainActor in + MainActor.assertIsolated() + try doWork() + } + heldTurn.end() + try await task.value + // The test ends the held turn off of the main actor. A task that hopped off of the main actor before ending its turn + // would end it on another thread too. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [false, true]) + } + #endif + // MARK: Private private let systemUnderTest = FIFOQueue() diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index ad8d9ee..f40f1b5 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -750,6 +750,48 @@ struct TurnsTests { #expect(systemUnderTest.isIdle) } + @Test + func reserve_whenEveryEarlierTurnHasEnded_reservesTurnThatWasCurrentWhenReserved() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + let secondTurn = systemUnderTest.reserve() + #expect(firstTurn.wasCurrentWhenReserved) + #expect(secondTurn.wasCurrentWhenReserved) + } + + @Test + func reserve_whileEarlierTurnHasNotEnded_reservesTurnThatWasNotCurrentWhenReserved() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + await secondTurn.begin() + secondTurn.end() + #expect(!secondTurn.wasCurrentWhenReserved) + } + + @MainActor + @Test + func begin_onMainActor_whenTurnWasCurrentWhenReserved_doesNotSuspend() async { + let systemUnderTest = Turns() + let turn = systemUnderTest.reserve() + let didOtherMainActorTaskRun = Mutex(false) + // This task can run only once the test suspends or returns, since the test holds the main actor. + let otherMainActorTask = Task { @MainActor in + didOtherMainActorTaskRun.withLock { $0 = true } + } + // Beginning a current turn runs on the caller's actor and returns without suspending, + // so it neither hops off of the main actor nor lets another main actor task run. + await turn.begin() + let didOtherMainActorTaskRunDuringBegin = didOtherMainActorTaskRun.withLock(\.self) + turn.end() + await otherMainActorTask.value + #expect(!didOtherMainActorTaskRunDuringBegin) + } + // MARK: Private /// Creates a task that takes `turn` and, once its turn begins, installs an escalation handler that uses `turns`,