Files
swift-mirror/stdlib/public/Concurrency/YieldingContinuation.swift
Philippe Hausler 4886bd56e4 [Concurrency] AsyncStream and AsyncThrowingStream
* Rework YieldingContinuation to service values in a buffered fashion

* Fix word size calculation for locks

* Handle terminal states and finished/failed storage

* Wrap yielding continuation into a more featureful type for better ergonomics

* Hope springs eternal, maybe windows works with this?

* Prevent value overflows at .max limits

* Add a cancellation handler

* Fix series tests missing continuation parameters

* Fix series tests for mutable itertaors

* Rename to a more general name for Series's inner continuation type

* Whitespace fixes and add more commentary about public functions on Series

* Restore YieldingContinuation for now with deprecations to favor Series

* Ensure onCancel is invoked in deinit phases, and eliminate a potential for double cancellation

* Make sure ThrowingSeries has the same nonmutating setter for onCancel as Series

* Add a swath of more unit tests that exersize cancellation behavior as well as throwing behaviors

* Remove work-around for async testing

* Fixup do/catch range to properly handle ThrowingSeries test

* Address naming consistency of resume result function

* Adopt the async main test setup

* More migration of tests to new async mechanisms

* Handle the double finish/throw case

* Ensure the dependency on Dispatch is built for the series tests (due to semaphore usage)

* Add import-libdispatch to run command for Series tests

* Use non-combine based timeout intervals (portable to linux) for dispatch semaphore

* Rename Series -> AsyncStream and resume functions to just yield, and correct a missing default Element.self value

* Fix missing naming change issue for yielding an error on AsyncThrowingStream

* Remove argument label of buffering from tests

* Extract buffer and throwing variants into their own file

* Slightly refactor for only needing to store the producer instead of producer and cancel

* Rename onCancel to onTermination

* Convert handler access into a function pair

* Add finished states to the termination handler event pipeline and a disambiguation enum to identify finish versus cancel

* Ensure all termination happens before event propigation (and outside of the locks) and warn against requirements for locking on terminate and enqueue

* Modified to use Deque to back the storage and move the storage to inner types; overall perf went from 200kE/sec to over 1ME/sec

* Update stdlib/public/Concurrency/AsyncStream.swift

Co-authored-by: Doug Gregor <dgregor@apple.com>

* Update stdlib/public/Concurrency/AsyncThrowingStream.swift

Co-authored-by: Doug Gregor <dgregor@apple.com>

* Update stdlib/public/Concurrency/AsyncStream.swift

Co-authored-by: Joseph Heck <heckj@mac.com>

* Update stdlib/public/Concurrency/AsyncThrowingStream.swift

Co-authored-by: Joseph Heck <heckj@mac.com>

* Update stdlib/public/Concurrency/AsyncThrowingStream.swift

Co-authored-by: Joseph Heck <heckj@mac.com>

* Update stdlib/public/Concurrency/AsyncThrowingStream.swift

Co-authored-by: Joseph Heck <heckj@mac.com>

* Update stdlib/public/Concurrency/AsyncStream.swift

Co-authored-by: Joseph Heck <heckj@mac.com>

* Update stdlib/public/Concurrency/AsyncThrowingStream.swift

Co-authored-by: Joseph Heck <heckj@mac.com>

* Remove local cruft for overlay disabling

* Remove local cruft for Dispatch overlay work

* Remove potential ABI impact for adding Deque

Co-authored-by: Doug Gregor <dgregor@apple.com>
Co-authored-by: Joseph Heck <heckj@mac.com>
2021-05-11 21:41:33 -07:00

201 lines
8.1 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
internal final class _YieldingContinuationStorage: UnsafeSendable {
var continuation: Builtin.RawUnsafeContinuation?
}
@available(SwiftStdlib 5.5, *)
@available(*, deprecated, message: "`YieldingContinuation` was replaced by `Series` and will be removed shortly.")
public struct YieldingContinuation<Element, Failure: Error>: Sendable {
let storage = _YieldingContinuationStorage()
/// Construct a YieldingContinuation.
///
/// This continuation type can be called more than once, unlike the unsafe and
/// checked counterparts. Each call to the yielding functions will resume any
/// awaiter on the next function. This type is inherently sendable and can
/// safely be used and stored in multiple task contexts.
public init() { }
/// Construct a YieldingContinuation with specific types including a failure.
///
/// This continuation type can be called more than once, unlike the unsafe and
/// checked counterparts. Each call to the yielding functions will resume any
/// awaiter on the next function. This type is inherently sendable and can
/// safely be used and stored in multiple task contexts.
public init(yielding: Element.Type, throwing: Failure.Type) { }
internal func _extract() -> UnsafeContinuation<Element, Error>? {
let raw = Builtin.atomicrmw_xchg_acqrel_Word(
Builtin.addressof(&storage.continuation),
UInt(bitPattern: 0)._builtinWordValue)
return unsafeBitCast(raw, to: UnsafeContinuation<Element, Error>?.self)
}
internal func _inject(
_ continuation: UnsafeContinuation<Element, Error>
) -> UnsafeContinuation<Element, Error>? {
let rawContinuation = unsafeBitCast(continuation, to: Builtin.Word.self)
let raw = Builtin.atomicrmw_xchg_acqrel_Word(
Builtin.addressof(&storage.continuation), rawContinuation)
return unsafeBitCast(raw, to: UnsafeContinuation<Element, Error>?.self)
}
/// Resume the task awaiting next by having it return normally from its
/// suspension point.
///
/// - Parameter value: The value to return from an awaiting call to next.
///
/// Unlike other continuations `YieldingContinuation` may resume more than
/// once. However if there are no potential awaiting calls to `next` this
/// function will return false, indicating that the caller needs to decide how
/// the behavior should be handled.
public func yield(_ value: __owned Element) -> Bool {
if let continuation = _extract() {
continuation.resume(returning: value)
return true
}
return false
}
/// Resume the task awaiting the continuation by having it throw an error
/// from its suspension point.
///
/// - Parameter error: The error to throw from an awaiting call to next.
///
/// Unlike other continuations `YieldingContinuation` may resume more than
/// once. However if there are no potential awaiting calls to `next` this
/// function will return false, indicating that the caller needs to decide how
/// the behavior should be handled.
public func yield(throwing error: __owned Failure) -> Bool {
if let continuation = _extract() {
continuation.resume(throwing: error)
return true
}
return false
}
}
@available(SwiftStdlib 5.5, *)
extension YieldingContinuation where Failure == Error {
/// Await a resume from a call to a yielding function.
///
/// - Return: The element that was yielded or a error that was thrown.
///
/// When multiple calls are awaiting a produced value from next any call to
/// yield will resume all awaiting calls to next with that value.
@available(*, deprecated, message: "`YieldingContinuation` was replaced by `Series` and will be removed shortly.")
public func next() async throws -> Element {
var existing: UnsafeContinuation<Element, Error>?
do {
let result = try await withUnsafeThrowingContinuation {
(continuation: UnsafeContinuation<Element, Error>) in
existing = _inject(continuation)
}
existing?.resume(returning: result)
return result
} catch {
existing?.resume(throwing: error)
throw error
}
}
}
@available(SwiftStdlib 5.5, *)
extension YieldingContinuation where Failure == Never {
/// Construct a YieldingContinuation with a specific Element type.
///
/// This continuation type can be called more than once, unlike the unsafe and
/// checked counterparts. Each call to the yielding functions will resume any
/// awaiter on the next function. This type is inherently sendable and can
/// safely be used and stored in multiple task contexts.
@available(*, deprecated, message: "`YieldingContinuation` was replaced by `Series` and will be removed shortly.")
public init(yielding: Element.Type) { }
/// Await a resume from a call to a yielding function.
///
/// - Return: The element that was yielded.
@available(*, deprecated, message: "`YieldingContinuation` was replaced by `Series` and will be removed shortly.")
public func next() async -> Element {
var existing: UnsafeContinuation<Element, Error>?
let result = try! await withUnsafeThrowingContinuation {
(continuation: UnsafeContinuation<Element, Error>) in
existing = _inject(continuation)
}
existing?.resume(returning: result)
return result
}
}
@available(SwiftStdlib 5.5, *)
extension YieldingContinuation {
/// Resume the task awaiting the continuation by having it either
/// return normally or throw an error based on the state of the given
/// `Result` value.
///
/// - Parameter result: A value to either return or throw from the
/// continuation.
///
/// Unlike other continuations `YieldingContinuation` may resume more than
/// once. However if there are no potential awaiting calls to `next` this
/// function will return false, indicating that the caller needs to decide how
/// the behavior should be handled.
@available(*, deprecated, message: "`YieldingContinuation` was replaced by `Series` and will be removed shortly.")
public func yield<Er: Error>(
with result: Result<Element, Er>
) -> Bool where Failure == Error {
switch result {
case .success(let val):
return self.yield(val)
case .failure(let err):
return self.yield(throwing: err)
}
}
/// Resume the task awaiting the continuation by having it either
/// return normally or throw an error based on the state of the given
/// `Result` value.
///
/// - Parameter result: A value to either return or throw from the
/// continuation.
///
/// Unlike other continuations `YieldingContinuation` may resume more than
/// once. However if there are no potential awaiting calls to `next` this
/// function will return false, indicating that the caller needs to decide how
/// the behavior should be handled.
@available(*, deprecated, message: "`YieldingContinuation` was replaced by `Series` and will be removed shortly.")
public func yield(with result: Result<Element, Failure>) -> Bool {
switch result {
case .success(let val):
return self.yield(val)
case .failure(let err):
return self.yield(throwing: err)
}
}
/// Resume the task awaiting the continuation by having it return normally
/// from its suspension point.
///
/// Unlike other continuations `YieldingContinuation` may resume more than
/// once. However if there are no potential awaiting calls to `next` this
/// function will return false, indicating that the caller needs to decide how
/// the behavior should be handled.
@available(*, deprecated, message: "`YieldingContinuation` was replaced by `Series` and will be removed shortly.")
public func yield() -> Bool where Element == Void {
return self.yield(())
}
}