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
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,43 @@ Task(on: cancellableQueue) {
}
```

## Checking whether a queue is idle

A `FIFOQueue` and an `ActorQueue` each have an `isIdle` property:

- A `FIFOQueue` is idle when every task you enqueued on it has finished. A task that is suspended at an `await` hasn't finished. Neither has a cancelled task: it keeps its place, and its operation still runs.
- An `ActorQueue` is idle when every task you enqueued on it has started running on the actor. The operations of its tasks might not have finished.

The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again.

For example, here's how an actor that keeps one `FIFOQueue` per document might remove the queues it no longer needs:

```swift
actor DocumentStore {
func save(_ contents: String, as name: String) -> Task<Void, Never> {
let queue = queues[name] ?? FIFOQueue()
queues[name] = queue
return Task(on: queue) {
await self.write(contents, as: name)
}
}

func removeIdleQueues() {
queues = queues.filter { !$0.value.isIdle }
}

private func write(_ contents: String, as name: String) async {
// Write implementation…
}

private var queues = [String: FIFOQueue]()
}
```

In the code above, the actor enqueues every task and reads `isIdle`, and it doesn't suspend between reading `isIdle` and removing the queue. So no task can be enqueued in between. A document you save after its queue is removed gets a new queue, and its task runs after the tasks of the removed queue, which have all finished.

`CancellableQueue` has no `isIdle` property. To check one, keep a reference to the queue it wraps, and read that queue's `isIdle`.

## 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`.
Expand Down
15 changes: 15 additions & 0 deletions Sources/AsyncQueue/ActorQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,21 @@ public final class ActorQueue<ActorType: Actor>: @unchecked Sendable {
weakExecutionContext = actor
}

/// Whether every task you enqueued on this queue has started running on the actor.
///
/// A task counts from the moment you enqueue it until it starts running on the actor.
/// So the queue can be idle while the operations of its tasks haven't finished.
/// A task runs alongside the code that enqueues it, so the task might start running on the actor before that code reads this property.
/// If that code is running on the actor, though, the task can't start running there until the code suspends or returns.
///
/// The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again.
/// If one actor enqueues every task on the queue, that actor can read this property and then remove an idle queue
/// without suspending between the read and the removal.
/// No task can be enqueued in between, so every task enqueued on the removed queue has started running on the queue's actor.
public var isIdle: Bool {
turns.isIdle
}

// MARK: Internal

/// Hands out turns to begin executing on the adopted actor, in the order in which tasks are enqueued.
Expand Down
44 changes: 44 additions & 0 deletions Sources/AsyncQueue/FIFOQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,50 @@ public final class FIFOQueue: Sendable {
self.priority = priority
}

// MARK: Public

/// Whether every task you enqueued on this queue has finished.
///
/// A task counts from the moment you enqueue it until its operation returns or throws.
/// A task that is suspended at an `await` hasn't finished,
/// so an operation that reads this property on its own queue always reads `false`.
/// A cancelled task hasn't finished either: it keeps its place in the queue, and its operation still runs.
/// A task runs alongside the code that enqueues it, so the task might finish before that code reads this property.
/// If the task's operation needs an actor that the code is running on, though,
/// the task can't finish until the code suspends or returns.
///
/// The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again.
/// If one actor enqueues every task on the queue, that actor can read this property and then safely remove an idle queue,
/// without suspending between the read and the removal.
/// No task can be enqueued in between, and a task that the actor enqueues afterward on a new queue
/// runs after every task on the removed queue, because they have all finished.
/// For example, an actor that keeps one queue per document can remove the queues of documents whose work has finished:
///
/// ```swift
/// actor DocumentStore {
/// func save(_ contents: String, as name: String) -> Task<Void, Never> {
/// let queue = queues[name] ?? FIFOQueue()
/// queues[name] = queue
/// return Task(on: queue) {
/// await self.write(contents, as: name)
/// }
/// }
///
/// func removeIdleQueues() {
/// queues = queues.filter { !$0.value.isIdle }
/// }
///
/// private func write(_ contents: String, as name: String) async {
/// // Write implementation…
/// }
///
/// private var queues = [String: FIFOQueue]()
/// }
/// ```
public var isIdle: Bool {
turns.isIdle
}

// MARK: Internal

/// Hands out turns to execute, in the order in which tasks are enqueued.
Expand Down
7 changes: 7 additions & 0 deletions Sources/AsyncQueue/Utilities/Turns.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ final class Turns: Sendable {
return Turn(turns: self, previousTicket: previousTicket, ticket: ticket)
}

/// Whether every turn reserved so far has ended.
///
/// A turn ends only after every turn reserved before it has ended, so every turn has ended once the most recently reserved turn has.
var isIdle: Bool {
state.withLock { $0.lastTicket?.hasEnded ?? true }
}

/// The number of tasks waiting for their turn whose priority is recorded. Used by tests.
var waitingTaskCount: Int {
state.withLock { $0.waitingTaskCounts.values.reduce(0, +) }
Expand Down
102 changes: 102 additions & 0 deletions Tests/AsyncQueueTests/ActorQueueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,108 @@ struct ActorQueueTests {
#expect(executor.wasEachJobEnqueuedOnMainQueue == [true, true])
}

@Test
func isIdle_onNewQueue_isTrue() {
#expect(systemUnderTest.isIdle)
}

@Test
func isIdle_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor() async {
let actor = ManuallyExecutedActor()
var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator()
let task = Task(on: actor.queue) { actor in
actor.queue.isIdle
}
// `Task(on:)` takes the task's place on the queue before it returns, and the task cannot be isolated to the actor
// until the test runs the actor's executor.
let isIdleAfterTaskWasEnqueued = actor.queue.isIdle
// Wait for the task to hop to the actor. It has begun executing, but it is not isolated to the actor yet.
_ = await enqueuedJobs.next()
let isIdleAfterTaskHoppedToActor = actor.queue.isIdle
actor.executor.runUntilIdle()
let isIdleWhileOperationExecuted = await task.value
#expect(!isIdleAfterTaskWasEnqueued)
#expect(!isIdleAfterTaskHoppedToActor)
#expect(isIdleWhileOperationExecuted)
}

@Test
func isIdle_whileLastOperationIsSuspended_isTrue() async {
let operationStarted = Semaphore()
let operationAllowedToReturn = Semaphore()
let task = Task(on: systemUnderTest) { _ in
await operationStarted.signal()
await operationAllowedToReturn.wait()
}
await operationStarted.wait()
// The task gave up its place on the queue once it was isolated to the actor, before its operation began.
let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle
await operationAllowedToReturn.signal()
await task.value
#expect(isIdleWhileOperationWasSuspended)
}

@Test
func isIdle_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActor() async {
let actor = ManuallyExecutedActor()
var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator()
// Each operation reads the property before it can suspend. The actor executes one job at a time, so the last task
// cannot be isolated to the actor while the first task's operation executes.
let firstTask = Task(on: actor.queue) { actor in
actor.queue.isIdle
}
let lastTask = Task(on: actor.queue) { actor in
actor.queue.isIdle
}
// Wait for the first task to hop to the actor, then run it. Its operation cannot execute before both tasks are enqueued.
_ = await enqueuedJobs.next()
actor.executor.runUntilIdle()
// Wait for the last task to hop to the actor, then run it if the previous call did not already.
_ = await enqueuedJobs.next()
actor.executor.runUntilIdle()
let isIdleWhileFirstOperationExecuted = await firstTask.value
let isIdleWhileLastOperationExecuted = await lastTask.value
#expect(!isIdleWhileFirstOperationExecuted)
#expect(isIdleWhileLastOperationExecuted)
}

@Test
func isIdle_onMainActorQueue_afterTaskIsEnqueuedWhileCallerHoldsMainActor_isFalseUntilOperationRuns() async {
// Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share.
let mainActorQueue = ActorQueue<MainActor>()
mainActorQueue.adoptExecutionContext(of: MainActor.shared)
// While this closure holds the main actor, the task cannot be isolated to it. The test cannot wait here for the task
// to hop to the main actor, so `mainTask_holdsTurnUntilItIsIsolatedToMainActor` covers when the task's turn ends.
let (task, isIdleAfterTaskWasEnqueued) = await MainActor.run {
let task = Task(on: mainActorQueue) {
mainActorQueue.isIdle
}
return (task, mainActorQueue.isIdle)
}
let isIdleWhileOperationExecuted = await task.value
#expect(!isIdleAfterTaskWasEnqueued)
#expect(isIdleWhileOperationExecuted)
}

@Test
func isIdle_onMainActorQueue_whileLastOperationIsSuspended_isTrue() async {
// Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share.
let mainActorQueue = ActorQueue<MainActor>()
mainActorQueue.adoptExecutionContext(of: MainActor.shared)
let operationStarted = Semaphore()
let operationAllowedToReturn = Semaphore()
let task = Task(on: mainActorQueue) {
await operationStarted.signal()
await operationAllowedToReturn.wait()
}
await operationStarted.wait()
// The task gave up its place on the queue once it was isolated to the main actor, before its operation began.
let isIdleWhileOperationWasSuspended = mainActorQueue.isIdle
await operationAllowedToReturn.signal()
await task.value
#expect(isIdleWhileOperationWasSuspended)
}

@Test
func task_seesCallersTaskLocalValues() async throws {
// Create the queue while a task-local value is bound: enqueued tasks must see their caller's values instead.
Expand Down
139 changes: 139 additions & 0 deletions Tests/AsyncQueueTests/FIFOQueueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,145 @@ struct FIFOQueueTests {
#expect(didNextTurnBeginAfterTaskCompleted)
}

@Test
func isIdle_onNewQueue_isTrue() {
#expect(systemUnderTest.isIdle)
}

@Test
func isIdle_afterTaskIsEnqueuedWhileOperationCannotReturn_isFalse() async {
let operationAllowedToReturn = Semaphore()
let task = Task(on: systemUnderTest) {
await operationAllowedToReturn.wait()
}
// `Task(on:)` takes the task's place on the queue before it returns, and the operation cannot return yet.
let isIdleAfterTaskWasEnqueued = systemUnderTest.isIdle
await operationAllowedToReturn.signal()
_ = await task.value
#expect(!isIdleAfterTaskWasEnqueued)
}

@Test
func isIdle_whileOperationIsSuspended_isFalseUntilOperationReturns() async {
let operationStarted = Semaphore()
let operationAllowedToReturn = Semaphore()
let task = Task(on: systemUnderTest) {
await operationStarted.signal()
await operationAllowedToReturn.wait()
}
await operationStarted.wait()
// The task holds its place on the queue until its operation returns.
let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle
await operationAllowedToReturn.signal()
await task.value
#expect(!isIdleWhileOperationWasSuspended)
#expect(systemUnderTest.isIdle)
}

@Test
func isIdle_whileThrowingOperationIsSuspended_isFalseUntilOperationThrows() async {
struct TestError: Error {}
let operationStarted = Semaphore()
let operationAllowedToThrow = Semaphore()
let task = Task(on: systemUnderTest) {
await operationStarted.signal()
await operationAllowedToThrow.wait()
throw TestError()
}
await operationStarted.wait()
// The task holds its place on the queue until its operation throws.
let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle
await operationAllowedToThrow.signal()
await #expect(throws: TestError.self) { try await task.value }
#expect(!isIdleWhileOperationWasSuspended)
#expect(systemUnderTest.isIdle)
}

@Test
func isIdle_whileOperationIsolatedToActorIsSuspended_isFalseUntilOperationReturns() async {
let operationStarted = Semaphore()
let operationAllowedToReturn = Semaphore()
let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in
await operationStarted.signal()
await operationAllowedToReturn.wait()
}
await operationStarted.wait()
// The task holds its place on the queue until its operation returns.
let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle
await operationAllowedToReturn.signal()
await task.value
#expect(!isIdleWhileOperationWasSuspended)
#expect(systemUnderTest.isIdle)
}

@Test
func isIdle_whileThrowingOperationIsolatedToActorIsSuspended_isFalseUntilOperationThrows() async {
struct TestError: Error {}
let operationStarted = Semaphore()
let operationAllowedToThrow = Semaphore()
let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in
await operationStarted.signal()
await operationAllowedToThrow.wait()
throw TestError()
}
await operationStarted.wait()
// The task holds its place on the queue until its operation throws.
let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle
await operationAllowedToThrow.signal()
await #expect(throws: TestError.self) { try await task.value }
#expect(!isIdleWhileOperationWasSuspended)
#expect(systemUnderTest.isIdle)
}

@Test
func isIdle_withCancelledTask_isFalseUntilItsOperationReturns() async {
let firstOperationAllowedToReturn = Semaphore()
let cancelledOperationStarted = Semaphore()
let cancelledOperationAllowedToReturn = Semaphore()
let firstTask = Task(on: systemUnderTest) {
await firstOperationAllowedToReturn.wait()
}
let cancelledTask = Task(on: systemUnderTest) {
await cancelledOperationStarted.signal()
await cancelledOperationAllowedToReturn.wait()
return Task.isCancelled
}
// The first operation cannot return yet, so this cancels the task while it waits on the queue.
cancelledTask.cancel()
await firstOperationAllowedToReturn.signal()
_ = await firstTask.value
// The cancelled task keeps its place on the queue, and its operation still runs.
let isIdleAfterFirstTaskCompleted = systemUnderTest.isIdle
await cancelledOperationStarted.wait()
let isIdleWhileCancelledOperationWasSuspended = systemUnderTest.isIdle
await cancelledOperationAllowedToReturn.signal()
let wasCancelledWhileOperationRan = await cancelledTask.value
#expect(!isIdleAfterFirstTaskCompleted)
#expect(!isIdleWhileCancelledOperationWasSuspended)
#expect(wasCancelledWhileOperationRan)
#expect(systemUnderTest.isIdle)
}

@Test
func isIdle_withSeveralTasks_isFalseUntilLastOperationReturns() async {
let firstOperationAllowedToReturn = Semaphore()
let lastOperationAllowedToReturn = Semaphore()
let firstTask = Task(on: systemUnderTest) {
await firstOperationAllowedToReturn.wait()
}
let lastTask = Task(on: systemUnderTest) {
await lastOperationAllowedToReturn.wait()
}
await firstOperationAllowedToReturn.signal()
_ = await firstTask.value
// The last operation cannot return yet, so the last task still holds its place on the queue.
let isIdleAfterFirstTaskCompleted = systemUnderTest.isIdle
await lastOperationAllowedToReturn.signal()
_ = await lastTask.value
#expect(!isIdleAfterFirstTaskCompleted)
#expect(systemUnderTest.isIdle)
}

@Test
func task_seesCallersTaskLocalValues() async throws {
let systemUnderTest = TestTaskLocal.$value.withValue("queue creator") {
Expand Down
Loading
Loading