Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shakemno/d2fb2a109729b13abdb91b1f8fb9393a to your computer and use it in GitHub Desktop.
Save shakemno/d2fb2a109729b13abdb91b1f8fb9393a to your computer and use it in GitHub Desktop.
class ThreadSafeCollection<Element> {
// Concurrent synchronization queue
private let queue = DispatchQueue(label: "ThreadSafeCollection.queue", attributes: .concurrent)
private var _elements: [Element] = []
var elements: [Element] {
var result: [Element] = []
queue.sync { // Read
result = _elements
}
return result
}
func append(_ element: Element) {
// Write with .barrier
// This can be performed synchronously or asynchronously not to block calling thread.
queue.async(flags: .barrier) {
self._elements.append(element)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment