Created
May 15, 2017 22:58
-
-
Save timshadel/8fb363b8b468c62479129d8a71e36643 to your computer and use it in GitHub Desktop.
A start of thread safe access to an array.
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
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