2017-04-22 52 views
0

查了doc,但沒有談到很多細節的實現。想知道是否對於大型陣列,它是否以併發方式執行?Swift數組的Map方法是否同時實現?

+0

地圖是一個同步的方法 –

+0

都能跟得上。對於大多數情況來說,多線程將比它的價值更高。不過,您可以自己輕鬆實現它。 – Alexander

+0

http://stackoverflow.com/a/41215383/3141234 – Alexander

回答

3

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") 
+0

讓我們[在聊天中繼續討論](http://chat.stackoverflow.com/rooms/142349/discussion-between-alexander-and-hamish)。 – Alexander

相關問題