Skip to content

Instantly share code, notes, and snippets.

@algal
Last active December 1, 2021 03:27
Show Gist options
  • Save algal/9425a4c22c0bcbcf7524ff3b057def14 to your computer and use it in GitHub Desktop.
Save algal/9425a4c22c0bcbcf7524ff3b057def14 to your computer and use it in GitHub Desktop.
/**
Gets and sets to this dictionary-like type are atomic.
Does not fully implement correct value semantics for copy
operations, since the contained queue is a reference type
and will be shared among copies of this object
*/
struct AtomicDictionary<KeyType:Hashable,ValueType>
{
private var internalDictionary:Dictionary<KeyType,ValueType> = [:]
private let queue = dispatch_queue_create("access queue", DISPATCH_QUEUE_CONCURRENT)
/* provide subscript accessors */
subscript(key: KeyType) -> ValueType? {
get {
var value : ValueType?
dispatch_sync(self.queue) { () -> Void in
value = self.internalDictionary[key]
}
return value
}
set {
setValue(newValue, forKey: key)
}
}
mutating func setValue(value: ValueType?, forKey key: KeyType) {
// use a dispatch barrier so writes are serialized
dispatch_barrier_sync(self.queue) { () -> Void in
self.internalDictionary[key] = value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment