Last active
          December 1, 2021 03:27 
        
      - 
      
- 
        Save algal/9425a4c22c0bcbcf7524ff3b057def14 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
    
  
  
    
  | /** | |
| 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