Created
March 23, 2018 08:05
-
-
Save astrokin/88674a1d905612e3c0b0b834e38da198 to your computer and use it in GitHub Desktop.
concurrentMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class ThreadSafe<A> { | |
private var _value: A | |
private let queue = DispatchQueue(label: "ThreadSafe") | |
init(_ value: A) { | |
self._value = value | |
} | |
var value: A { | |
return queue.sync { _value } | |
} | |
func atomically(_ transform: (inout A) -> ()) { | |
queue.sync { | |
transform(&self._value) | |
} | |
} | |
} | |
extension Array { | |
func concurrentMap<B>(_ transform: @escaping (Element) -> B) -> [B] { | |
let result = ThreadSafe(Array<B?>(repeating: nil, count: count)) | |
DispatchQueue.concurrentPerform(iterations: count) { idx in | |
let element = self[idx] | |
let transformed = transform(element) | |
result.atomically { | |
$0[idx] = transformed | |
} | |
} | |
return result.value.map { $0! } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment