mirror of
https://github.com/apple/swift-async-algorithms
synced 2026-11-23 04:14:23 +00:00
* Remove `AsyncIterator: Sendable` requirement from merge # Motivation Currently a lot of the operator implementations in here that consume other `AsyncSequence`s require the `AsyncIterator` to be `Sendable`. This is mostly due to the fact that we are calling `makeAsyncIterator` on the upstream `AsyncSequence` and then pass that iterator around to various newly spawned `Task`s. This has two downsides: 1. It only allows users to use operators like `merge` if their `AsyncSequence.AsyncIterator` is `Sendable` 2. In merge we are creating new `Task`s for every new demand. Creating `Task`s is not cheap. My main goal of this PR was to remove the `Sendable` constraint from `merge`. # Modification This PR overhauls the complete inner workings of the `AsyncMerge2Sequence`. It does a couple of things: 1. The main change is that instead of creating new `Task`s for every demand, we are creating one `Task` when the `AsyncIterator` is created. This task has as child task for every upstream sequence. 2. When calling `next` we are signalling the child tasks to demand from the upstream 3. A new state machine that is synchronizing the various concurrent operations that can happen 4. Handling cancellation since we are creating a bunch of continuations. # Result In the end, this PR swaps the implementation of `AsyncMerge2Sequence` and drops the `Sendable` constraint and passes all tests. Furthermore, on my local performance testing I saw up 50% speed increase in throughput. # Open points 1. I need to make this sequence re-throwing but before going down that rabbit whole I wanna get buy-in on the implementation. 2. We should discuss and document if `merge` and other operators are hot or cold, i.e. if they only request if they got downstream demand 3. I need to switch `AsyncMerge3Sequence` over to the same iplementation * Split logic into multiple files, adapt merge3 and incorporate PR feedback * Add more tests and fix upstream throw behaviour * Remove internal class from the sequence * Setup task after first next * Remove unnecessary tests
139 lines
3.8 KiB
Swift
139 lines
3.8 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// 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
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
#if canImport(Darwin)
|
|
@_implementationOnly import Darwin
|
|
#elseif canImport(Glibc)
|
|
@_implementationOnly import Glibc
|
|
#elseif canImport(WinSDK)
|
|
@_implementationOnly import WinSDK
|
|
#endif
|
|
|
|
internal struct Lock {
|
|
#if canImport(Darwin)
|
|
typealias Primitive = os_unfair_lock
|
|
#elseif canImport(Glibc)
|
|
typealias Primitive = pthread_mutex_t
|
|
#elseif canImport(WinSDK)
|
|
typealias Primitive = SRWLOCK
|
|
#endif
|
|
|
|
typealias PlatformLock = UnsafeMutablePointer<Primitive>
|
|
let platformLock: PlatformLock
|
|
|
|
private init(_ platformLock: PlatformLock) {
|
|
self.platformLock = platformLock
|
|
}
|
|
|
|
fileprivate static func initialize(_ platformLock: PlatformLock) {
|
|
#if canImport(Darwin)
|
|
platformLock.initialize(to: os_unfair_lock())
|
|
#elseif canImport(Glibc)
|
|
pthread_mutex_init(platformLock, nil)
|
|
#elseif canImport(WinSDK)
|
|
InitializeSRWLock(platformLock)
|
|
#endif
|
|
}
|
|
|
|
fileprivate static func deinitialize(_ platformLock: PlatformLock) {
|
|
#if canImport(Glibc)
|
|
pthread_mutex_destroy(platformLock)
|
|
#endif
|
|
platformLock.deinitialize(count: 1)
|
|
}
|
|
|
|
fileprivate static func lock(_ platformLock: PlatformLock) {
|
|
#if canImport(Darwin)
|
|
os_unfair_lock_lock(platformLock)
|
|
#elseif canImport(Glibc)
|
|
pthread_mutex_lock(platformLock)
|
|
#elseif canImport(WinSDK)
|
|
AcquireSRWLockExclusive(platformLock)
|
|
#endif
|
|
}
|
|
|
|
fileprivate static func unlock(_ platformLock: PlatformLock) {
|
|
#if canImport(Darwin)
|
|
os_unfair_lock_unlock(platformLock)
|
|
#elseif canImport(Glibc)
|
|
pthread_mutex_unlock(platformLock)
|
|
#elseif canImport(WinSDK)
|
|
ReleaseSRWLockExclusive(platformLock)
|
|
#endif
|
|
}
|
|
|
|
static func allocate() -> Lock {
|
|
let platformLock = PlatformLock.allocate(capacity: 1)
|
|
initialize(platformLock)
|
|
return Lock(platformLock)
|
|
}
|
|
|
|
func deinitialize() {
|
|
Lock.deinitialize(platformLock)
|
|
}
|
|
|
|
func lock() {
|
|
Lock.lock(platformLock)
|
|
}
|
|
|
|
func unlock() {
|
|
Lock.unlock(platformLock)
|
|
}
|
|
|
|
/// Acquire the lock for the duration of the given block.
|
|
///
|
|
/// This convenience method should be preferred to `lock` and `unlock` in
|
|
/// most situations, as it ensures that the lock will be released regardless
|
|
/// of how `body` exits.
|
|
///
|
|
/// - Parameter body: The block to execute while holding the lock.
|
|
/// - Returns: The value returned by the block.
|
|
func withLock<T>(_ body: () throws -> T) rethrows -> T {
|
|
self.lock()
|
|
defer {
|
|
self.unlock()
|
|
}
|
|
return try body()
|
|
}
|
|
|
|
// specialise Void return (for performance)
|
|
func withLockVoid(_ body: () throws -> Void) rethrows -> Void {
|
|
try self.withLock(body)
|
|
}
|
|
}
|
|
|
|
struct ManagedCriticalState<State> {
|
|
private final class LockedBuffer: ManagedBuffer<State, Lock.Primitive> {
|
|
deinit {
|
|
withUnsafeMutablePointerToElements { Lock.deinitialize($0) }
|
|
}
|
|
}
|
|
|
|
private let buffer: ManagedBuffer<State, Lock.Primitive>
|
|
|
|
init(_ initial: State) {
|
|
buffer = LockedBuffer.create(minimumCapacity: 1) { buffer in
|
|
buffer.withUnsafeMutablePointerToElements { Lock.initialize($0) }
|
|
return initial
|
|
}
|
|
}
|
|
|
|
func withCriticalRegion<R>(_ critical: (inout State) throws -> R) rethrows -> R {
|
|
try buffer.withUnsafeMutablePointers { header, lock in
|
|
Lock.lock(lock)
|
|
defer { Lock.unlock(lock) }
|
|
return try critical(&header.pointee)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension ManagedCriticalState: @unchecked Sendable where State: Sendable { }
|