diff --git a/README.md b/README.md index cde1208..2324a87 100644 --- a/README.md +++ b/README.md @@ -56,11 +56,6 @@ This package is the home for these APIs. Development and API design take place o - [`Dictionary.init(_:uniquingKeysWith:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence, using a combining closure to determine the value for any duplicate keys. - [`Dictionary.init(grouping:by:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key. - [`SetAlgebra.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new set from an asynchronous sequence of items. - - -#### Task management - -- [`Task.select(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Select.md): Determine the first task to complete of a sequence of tasks. #### Effects diff --git a/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/AsyncAlgorithms.md b/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/AsyncAlgorithms.md index 8a0cbbf..1f18bc0 100644 --- a/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/AsyncAlgorithms.md +++ b/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/AsyncAlgorithms.md @@ -30,7 +30,6 @@ This package has three main goals: - - - -- - - - diff --git a/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Select.md b/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Select.md deleted file mode 100644 index fb0389c..0000000 --- a/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Select.md +++ /dev/null @@ -1,53 +0,0 @@ -# Task.select - -* Author(s): [Philippe Hausler](https://github.com/phausler) - -[ -[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/TaskSelect.swift) | -[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestTaskSelect.swift) -] - -## Introduction - -A fundamental part of many algorithms is being able to select the first resolved task from a given list of active tasks. This enables algorithms like `debounce` or `merge`. - -## Proposed Solution - -Selecting the first task to complete from a list of active tasks is a similar algorithm to `select(2)`. This has similar behavior to `TaskGroup` except that instead of child tasks this function transacts upon already running tasks and does not cancel them upon completion of the selection and does not need to await for the completion of all of the tasks in the list to select. - -```swift -extension Task { - public static func select( - _ tasks: Tasks - ) async -> Task - - public static func select( - _ tasks: Task... - ) async -> Task -} -``` - -## Detailed Design - -Given any number of `Task` objects that share the same `Success` and `Failure` types; `Task.select` will suspend and await each tasks result and resume when the first task has produced a result. While the calling task of `Task.select` is suspended if that task is cancelled the tasks being selected receive the cancel. This is similar to the family of `TaskGroup` with a few behavioral and structural differences. - -The `withTaskGroup` API will create efficient child tasks. -The `Task.select` API takes pre-existing tasks. - -The `withTaskGroup` API will await all child tasks to be finished before returning. -The `Task.select` API will await for the first task to be finished before returning. - -The `withTaskGroup` API will cancel all outstanding child tasks upon awaiting its return. -The `Task.select` API will let the non selected tasks keep on running. - -The `withTaskGroup` can support having 0 child tasks. -The `Task.select` API requires at least 1 task to select over, anything less is a programmer error. - -This means that `withTaskGroup` is highly suited to run work in parallel, whereas `Task.select` is intended to find the first task that provides a value. There is inherent additional cost to the non-child tasks so `Task.select` should not be used as a replacement for anywhere that is more suitable as a group, but offers more potential for advanced algorithms. - -## Alternatives Considered - -## Future Directions - - -## Credits/Inspiration diff --git a/Sources/AsyncAlgorithms/TaskSelect.swift b/Sources/AsyncAlgorithms/TaskSelect.swift deleted file mode 100644 index b620824..0000000 --- a/Sources/AsyncAlgorithms/TaskSelect.swift +++ /dev/null @@ -1,78 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Async Algorithms open source project -// -// Copyright (c) 2022 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -struct TaskSelectState: Sendable { - var complete = false - var tasks: [Task]? = [] - - mutating func add(_ task: Task) -> Task? { - if var tasks = tasks { - tasks.append(task) - self.tasks = tasks - return nil - } else { - return task - } - } -} - -extension Task { - /// Determine the first task to complete of a sequence of tasks. - /// - /// - Parameters: - /// - tasks: The running tasks to obtain a result from - /// - Returns: The first task to complete from the running tasks - public static func select( - _ tasks: Tasks - ) async -> Task - where Tasks.Element == Task { - let state = ManagedCriticalState(TaskSelectState()) - return await withTaskCancellationHandler { - await withUnsafeContinuation { continuation in - for task in tasks { - Task { - _ = await task.result - let winner = state.withCriticalRegion { state -> Bool in - defer { state.complete = true } - return !state.complete - } - if winner { - continuation.resume(returning: task) - } - } - state.withCriticalRegion { state in - state.add(task) - }?.cancel() - } - } - } onCancel: { - let tasks = state.withCriticalRegion { state -> [Task] in - defer { state.tasks = nil } - return state.tasks ?? [] - } - for task in tasks { - task.cancel() - } - } - } - - /// Determine the first task to complete of a list of tasks. - /// - /// - Parameters: - /// - tasks: The running tasks to obtain a result from - /// - Returns: The first task to complete from the running tasks - public static func select( - _ tasks: Task... - ) async -> Task { - await select(tasks) - } -} - diff --git a/Tests/AsyncAlgorithmsTests/TestTaskSelect.swift b/Tests/AsyncAlgorithmsTests/TestTaskSelect.swift deleted file mode 100644 index a3b4962..0000000 --- a/Tests/AsyncAlgorithmsTests/TestTaskSelect.swift +++ /dev/null @@ -1,99 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Async Algorithms open source project -// -// Copyright (c) 2022 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -@preconcurrency import XCTest -import Dispatch -import AsyncAlgorithms - -final class TestTaskSelect: XCTestCase { - func test_first() async { - let firstValue = await Task.select(Task { - return 1 - }, Task { - if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) { - try! await Task.sleep(until: .now + .seconds(2), clock: .continuous) - } else { - try! await Task.sleep(nanoseconds: 2_000_000_000) - } - return 2 - }).value - XCTAssertEqual(firstValue, 1) - } - - func test_second() async { - let firstValue = await Task.select(Task { - if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) { - try! await Task.sleep(until: .now + .seconds(2), clock: .continuous) - } else { - try! await Task.sleep(nanoseconds: 2_000_000_000) - } - return 1 - }, Task { - return 2 - }).value - XCTAssertEqual(firstValue, 2) - } - - func test_throwing() async { - do { - _ = try await Task.select(Task { () async throws -> Int in - if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) { - try await Task.sleep(until: .now + .seconds(2), clock: .continuous) - } else { - try await Task.sleep(nanoseconds: 2_000_000_000) - } - return 1 - }, Task { () async throws -> Int in - throw NSError(domain: NSCocoaErrorDomain, code: -1, userInfo: nil) - }).value - XCTFail() - } catch { - XCTAssertEqual((error as NSError).code, -1) - } - } - - func test_cancellation() async { - let firstReady = expectation(description: "first ready") - let secondReady = expectation(description: "second ready") - let firstCancelled = expectation(description: "first cancelled") - let secondCancelled = expectation(description: "second cancelled") - let task = Task { - _ = await Task.select(Task { - await withTaskCancellationHandler { () -> Int in - firstReady.fulfill() - if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) { - try? await Task.sleep(until: .now + .seconds(2), clock: .continuous) - } else { - try? await Task.sleep(nanoseconds: 2_000_000_000) - } - return 1 - } onCancel: { - firstCancelled.fulfill() - } - }, Task { - await withTaskCancellationHandler { () -> Int in - secondReady.fulfill() - if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) { - try? await Task.sleep(until: .now + .seconds(2), clock: .continuous) - } else { - try? await Task.sleep(nanoseconds: 2_000_000_000) - } - return 1 - } onCancel: { - secondCancelled.fulfill() - } - }) - } - wait(for: [firstReady, secondReady], timeout: 1.0) - task.cancel() - wait(for: [firstCancelled, secondCancelled], timeout: 1.0) - } -}