gpt4 book ai didi

arrays - Swift Array 的 Map 方法是否并发实现?

转载 作者:搜寻专家 更新时间:2023-11-01 06:03:36 28 4
gpt4 key购买 nike

检查了 doc ,但没有谈到很多实现细节。想知道对于一个大数组,是否并发执行?

最佳答案

Arraymap 实现具体来说不执行任何多线程,但也没有说明您不能进行并发实现。下面是一个被泛化为适用于任何 Sequence 的代码:

import Dispatch


class SharedSynchronizedArray<T> {
var array = [T]()
let operationQueue = DispatchQueue(label: "SharedSynchronizedArray")

func append(_ newElement: T) {
operationQueue.sync {
array.append(newElement)
}
}
}

public struct ConcurrentSequence<Base, Element>: Sequence
where Base: Sequence, Element == Base.Iterator.Element {
let base: Base

public func makeIterator() -> Base.Iterator {
return base.makeIterator()
}

public func map<T>(_ transform: @escaping (Element) -> T) -> [T] {
let group = DispatchGroup()

let resultsStorageQueue = DispatchQueue(label: "resultStorageQueue")
let results = SharedSynchronizedArray<T>()

let processingQueue = DispatchQueue(
label: "processingQueue",
attributes: [.concurrent]
)

for element in self {
group.enter()
print("Entered DispatchGroup for \(element)")

var result: T?
let workItem = DispatchWorkItem{ result = transform(element) }

processingQueue.async(execute: workItem)

resultsStorageQueue.async {
workItem.wait()
guard let unwrappedResult = result else {
fatalError("The work item was completed, but the result wasn't set!")
}
results.append(unwrappedResult)


group.leave()
print("Exited DispatchGroup for \(element)")
}
}
print("Started Waiting on DispatchGroup")
group.wait()
print("DispatchGroup done")

return results.array
}


}

public extension Sequence {
public var parallel: ConcurrentSequence<Self, Iterator.Element> {
return ConcurrentSequence(base: self)
}
}

print("Start")

import Foundation

let input = Array(0..<100)
let output: [Int] = input.parallel.map {
let randomDuration = TimeInterval(Float(arc4random()) / Float(UInt32.max))
Thread.sleep(forTimeInterval: randomDuration)
print("Transforming \($0)")
return $0 * 2
}

print(output)
// print(output.parallel.filter{ $0 % 3 == 0 })

print("Done")

关于arrays - Swift Array 的 Map 方法是否并发实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43555251/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com