timshadel
5/15/2017 - 10:58 PM

A start of thread safe access to an array.

A start of thread safe access to an array.

struct SafeArray<Element> {

    private let multiReaderQueue: DispatchQueue
    private var array = [Element]()

    init() {
        multiReaderQueue = DispatchQueue(label: "safeArray.internal", attributes: .concurrent)
    }

    var count: Int { return read { self.array.count } }
    var last: Element? { return read { self.array.last } }

    mutating func append(_ element: Element) {
        write { self.array.append(element) }
    }

    private func read<T>(execute block: () -> T) -> T {
        return multiReaderQueue.sync(execute: block)
    }

    private func write<T>(execute block: () -> T) -> T {
        return multiReaderQueue.sync(flags: .barrier, execute: block)
    }

}