Skip to content

Instantly share code, notes, and snippets.

@timshadel
Created May 15, 2017 22:58
Show Gist options
  • Save timshadel/8fb363b8b468c62479129d8a71e36643 to your computer and use it in GitHub Desktop.
Save timshadel/8fb363b8b468c62479129d8a71e36643 to your computer and use it in GitHub Desktop.
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment