Created
December 13, 2018 05:20
-
-
Save ha1f/4031c1f2fd7945816723082694c2db8e to your computer and use it in GitHub Desktop.
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
import Foundation | |
final class ThreadSafeCollection<T> { | |
private let _lock = NSRecursiveLock() | |
private var _observers: [Int: T] = [:] | |
private var _nextKey = 0 | |
func insert(_ observer: T) -> Int { | |
_lock.lock() | |
defer { | |
_lock.unlock() | |
} | |
let key = _nextKey | |
_observers[key] = observer | |
_nextKey = key + 1 | |
return key | |
} | |
func remove(forKey key: Int) { | |
_lock.lock() | |
defer { | |
_lock.unlock() | |
} | |
_observers.removeValue(forKey: key) | |
} | |
} | |
extension ThreadSafeCollection: Sequence { | |
func makeIterator() -> DictionaryIterator<Int, T> { | |
return _observers.makeIterator() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment