Last active
July 27, 2020 19:59
-
-
Save dmytro-anokhin/4a5848606887871920f539629676d948 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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