Skip to content
Closed
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
70 changes: 70 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,76 @@ jobs:
run: sudo xcode-select --switch /Applications/Xcode_27.2.app/Contents/Developer
- name: Build and Test Framework
run: xcrun swift test -c release -Xswiftc -enable-testing
tsan:
name: "Thread Sanitizer on macOS"
runs-on: xcode-27
# A test that deadlocks keeps the test run from ending, so stop the
# job after 30 minutes rather than at GitHub's six-hour default.
timeout-minutes: 30
permissions:
contents: read
steps:
- name: Checkout Repo
uses: actions/checkout@v7
- name: Select Xcode Version
run: sudo xcode-select --switch /Applications/Xcode_27.2.app/Contents/Developer
- name: Build With Thread Sanitizer
run: xcrun swift build --build-tests --sanitize=thread
- name: Test With Thread Sanitizer
run: xcrun swift test --skip-build --sanitize=thread
ios18-export-spike:
name: "Spike: export the iOS 18 runtime with Xcode 26"
runs-on: macos-15
timeout-minutes: 50
permissions:
contents: read
steps:
- name: Export the iOS 18.5 Simulator Runtime
run: |
set -x
sudo xcode-select --switch /Applications/Xcode_26.1.1.app/Contents/Developer
mkdir -p runtime
SECONDS=0
# The image has iOS 18.5 installed as a disk image. Copy that image
# directly; `xcodebuild -downloadPlatform -exportPath` exports it too,
# but fails at random with "Unable to connect to simulator."
xcrun simctl runtime list -j > runtimes.json
image=$(python3 -c 'import json,sys; d=json.load(open("runtimes.json")); print(next((v["path"] for v in d.values() if v.get("build") == "22F77" and v.get("path")), ""))')
if [ -n "$image" ]; then
cp "$image" runtime/iphonesimulator_18.5_22F77.dmg
else
cat runtimes.json
sudo xcodebuild -runFirstLaunch
sudo xcodebuild -downloadPlatform iOS -buildVersion 22F77 -exportPath runtime || echo "xcodebuild exited with $?"
sudo chown -R "$(whoami)" runtime
fi
echo "Export took ${SECONDS}s"
ls -la runtime
test -f runtime/iphonesimulator_18.5_22F77.dmg
- name: Upload the Runtime
uses: actions/upload-artifact@v4
with:
name: ios-18-5-runtime
path: runtime
compression-level: 0
retention-days: 1
ios18-spike:
name: "Spike: test on the iOS 18 runtime with Xcode 27"
needs: ios18-export-spike
runs-on: xcode-27
timeout-minutes: 50
permissions:
contents: read
steps:
- name: Checkout Repo
uses: actions/checkout@v7
- name: Download the Runtime
uses: actions/download-artifact@v4
with:
name: ios-18-5-runtime
path: runtime
- name: Install the Runtime and Test on It
run: Scripts/spike-old-simulator.sh
linux:
name: "Build and Test on Linux"
runs-on: ubuntu-24.04
Expand Down
44 changes: 41 additions & 3 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 All @@ -276,7 +313,7 @@ Your operation sees the [task-local values](https://developer.apple.com/document
### Priority

- A task runs at the priority you pass to `Task(on:)`. If you pass `nil`, it runs at the priority of the code that enqueues it, as with `Task.init`.
- `FIFOQueue(priority:)` gives each of the queue's tasks at least that priority. A task that would run at a lower priority runs at the queue's priority instead.
- `FIFOQueue(priority:)` and `ActorQueue(priority:)` give each of the queue's tasks at least that priority. A task that would run at a lower priority runs at the queue's priority instead. `MainActor.queue` has no priority of its own.
- When a higher-priority task awaits a task's value, Swift raises, or *escalates*, that task's priority, as it does for any task.
- On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, a task that waits in a queue also raises the priority of the tasks ahead of it to its own priority. That way, the tasks ahead of a high-priority task don't run at a lower priority while it waits. On earlier releases, the tasks ahead keep their own priority.
- A task keeps a raised priority until it finishes.
Expand All @@ -295,9 +332,10 @@ Cancellation is [cooperative](https://docs.swift.org/swift-book/documentation/th
- **Swift and platform versions.** Version 2.0 requires Swift 6.4 and newer platform versions; see [Installation](#installation). Update your toolchain and deployment targets.
- **Priority.** An operation you enqueue without a priority now runs at the priority of the code that enqueues it. In 1.x, a `FIFOQueue` created without a priority ran it at `.medium`, and an `ActorQueue` ran it at the priority of the code that created the queue.
- On a `FIFOQueue`, a task enqueued from low-priority code now runs at low priority, and the tasks behind it wait for it. To keep the 1.x priority, create the queue with `FIFOQueue(priority: .medium)`.
- On an `ActorQueue`, pass `priority:` to `Task(on:)` when you enqueue important work from low-priority code.
- On an `ActorQueue`, a task enqueued from low-priority code now runs at low priority. To keep its tasks at the 1.x priority or higher, create the queue with the priority of the code that creates it, such as `ActorQueue(priority: .medium)`.
- On `MainActor.queue`, pass `priority:` to `Task(on:)` when you enqueue important work from low-priority code.
- **Task-local values.** An operation now sees the task-local values of the code that enqueues it. In 1.x, an operation on an `ActorQueue` saw the values of the code that created the queue, and an operation on a `FIFOQueue` saw none. You need to change your code only if an operation relied on the 1.x values.
- **Queue names.** `FIFOQueue(name:priority:)` and `ActorQueue(name:)` are removed, because operations now run in the task that `Task(on:)` returns. Use `FIFOQueue(priority:)` and `ActorQueue()`, and pass `name:` to `Task(on:)` to name each task instead.
- **Queue names.** `FIFOQueue(name:priority:)` and `ActorQueue(name:)` are removed, because operations now run in the task that `Task(on:)` returns. Use `FIFOQueue(priority:)` and `ActorQueue(priority:)`, and pass `name:` to `Task(on:)` to name each task instead.

## Installation

Expand Down
68 changes: 68 additions & 0 deletions Scripts/spike-old-simulator.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/bin/bash
# Spike, not for merging: can Xcode 27.2 run the tests on an iOS 18.5
# simulator runtime that Xcode 26.1.1 exported on another runner?
set -x
export DEVELOPER_DIR=/Applications/Xcode_27.2.app/Contents/Developer
ls -la runtime

echo "::group::Free disk space"
df -h /
xcrun simctl runtime list
SECONDS=0
# Keep only the 27.2 runtime of each platform: the jobs test on those.
for id in $(xcrun simctl runtime list | grep -v ' 27\.2 (' | grep -v '24B91016s' | grep -oE '[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}'); do
sudo xcrun simctl runtime delete "$id" || true
done
# The iPhone-specific 27.2 variant isn't used either.
for id in $(xcrun simctl runtime list | grep '24B91016s' | grep -oE '[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}'); do
sudo xcrun simctl runtime delete "$id" || true
done
for attempt in $(seq 1 60); do
xcrun simctl runtime list | grep -q 'Deleting' || break
sleep 5
done
echo "Deleting runtimes took ${SECONDS}s"
xcrun simctl runtime list
df -h /
echo "::endgroup::"

echo "::group::Add the runtime"
find runtime -maxdepth 2 -print
sudo xcodebuild -runFirstLaunch
SECONDS=0
for image in runtime/*; do
sudo xcodebuild -importPlatform "$image"
echo "xcodebuild -importPlatform $image exit $? after ${SECONDS}s"
if ! xcrun simctl list runtimes | grep -q 'iOS 18\.'; then
SECONDS=0
sudo xcrun simctl runtime add "$image"
echo "simctl runtime add $image exit $? after ${SECONDS}s"
fi
done
xcrun simctl runtime list
xcrun simctl list runtimes
echo "::endgroup::"

echo "::group::Prebuild the dyld shared cache"
SECONDS=0
sudo xcrun simctl runtime dyld_shared_cache update --all
echo "dyld_shared_cache update exit $? after ${SECONDS}s"
echo "::endgroup::"

RUNTIME=$(xcrun simctl list runtimes | grep 'iOS 18\.' | tail -1 | grep -o 'com\.apple\.CoreSimulator\.SimRuntime\.iOS-18-[0-9-]*')
if [ -z "$RUNTIME" ]; then
echo "::error::Xcode 27.2 does not list an iOS 18 runtime after adding the image."
exit 1
fi
UDID=$(xcrun simctl create "iPad iOS 18" "com.apple.CoreSimulator.SimDeviceType.iPad-10th-generation" "$RUNTIME")
echo "Created $UDID on $RUNTIME"

echo "::group::Test with Xcode 27.2 on the iOS 18 simulator"
SECONDS=0
xcodebuild -scheme swift-async-queue -sdk iphonesimulator \
-derivedDataPath .build/derivedData/iOS18 -PBXBuildsContinueAfterErrors=0 \
OTHER_SWIFT_FLAGS=-warnings-as-errors -destination "id=$UDID" build test
STATUS=$?
echo "Test exit $STATUS after ${SECONDS}s"
echo "::endgroup::"
exit $STATUS
42 changes: 37 additions & 5 deletions Sources/AsyncQueue/ActorQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,13 @@ public final class ActorQueue<ActorType: Actor>: @unchecked Sendable {
// MARK: Initialization

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

// MARK: Public

Expand All @@ -70,11 +76,29 @@ 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.
let turns = Turns()

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

// MARK: Fileprivate

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

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