Forked from dmytro-anokhin/Concurrency_DispatchBarrier.swift
Created
July 27, 2020 19:59
-
-
Save shakemno/d2fb2a109729b13abdb91b1f8fb9393a 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