diff --git a/Sources/Algorithms/Concurrent.swift b/Sources/Algorithms/Concurrent.swift new file mode 100644 index 0000000..cc8c40b --- /dev/null +++ b/Sources/Algorithms/Concurrent.swift @@ -0,0 +1,114 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 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 +// +//===----------------------------------------------------------------------===// + +@available(macOS 12.0, *) +extension Collection { + public func parallelMap( + parallelism requestedParallelism: Int? = nil, + _ transform: @escaping (Element) async throws -> T) async throws -> [T] + { + let defaultParallelism = 2 + let parallelism = requestedParallelism ?? defaultParallelism + + let count = self.count + let buffer = UnsafeMutableBufferPointer.allocate(capacity: count) + defer { buffer.deallocate() } + + return try await withThrowingTaskGroup(of: (Int, T).self) { group in + var current = self.startIndex + var submitted = 0 + + func submitNext() async throws { + group.async { [submitted, i = current] in + let value = try await transform(self[i]) + return (submitted, value) + } + submitted += 1 + formIndex(after: ¤t) + } + + // Submit initial tasks. + for _ in 0.. Bool) async throws -> Index? + { + let defaultParallelism = 2 + let parallelism = requestedParallelism ?? defaultParallelism + var found: Index? + + return try await withThrowingTaskGroup(of: Index?.self) { group in + var current = self.startIndex + + func submitNext() async throws { + group.async { [i = current] in + try await predicate(self[i]) ? i : nil + } + formIndex(after: ¤t) + } + + // Submit initial tasks. + for _ in 0.. 5 }) + XCTAssertEqual(expected, actual) + } +}