Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a race condition that caused withTimeout to not escalate the priority of the body #1780

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
11 changes: 8 additions & 3 deletions Sources/SwiftExtensions/AsyncUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,14 @@ package func withTimeout<T: Sendable>(
_ duration: Duration,
_ body: @escaping @Sendable () async throws -> T
) async throws -> T {
// Get the priority with which to launch the body task here so that we can pass the same priority as the initial
// priority to `withTaskPriorityChangedHandler`. Otherwise, we can get into a race condition where bodyTask gets
// launched with a low priority, then the priority gets elevated before we call with `withTaskPriorityChangedHandler`,
// we thus don't receive a `taskPriorityChanged` and hence never increase the priority of `bodyTask`.
let priority = Task.currentPriority
var mutableTasks: [Task<Void, Error>] = []
let stream = AsyncThrowingStream<T, Error> { continuation in
let bodyTask = Task<Void, Error> {
let bodyTask = Task<Void, Error>(priority: priority) {
do {
let result = try await body()
continuation.yield(result)
Expand All @@ -187,7 +192,7 @@ package func withTimeout<T: Sendable>(
}
}

let timeoutTask = Task {
let timeoutTask = Task(priority: priority) {
try await Task.sleep(for: duration)
continuation.yield(with: .failure(TimeoutError()))
bodyTask.cancel()
Expand All @@ -197,7 +202,7 @@ package func withTimeout<T: Sendable>(

let tasks = mutableTasks

return try await withTaskPriorityChangedHandler {
return try await withTaskPriorityChangedHandler(initialPriority: priority) {
for try await value in stream {
return value
}
Expand Down
1 change: 0 additions & 1 deletion Tests/SKSupportTests/AsyncUtilsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ final class AsyncUtilsTests: XCTestCase {
}

func testWithTimeoutEscalatesPriority() async throws {
try XCTSkipIf(true, "Flakey test: rdar://137640122")
let expectation = self.expectation(description: "Timeout started")
let task = Task(priority: .background) {
// We don't actually hit the timeout. It's just a large value.
Expand Down