-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConcurrentDictionary.swift
71 lines (57 loc) · 1.63 KB
/
ConcurrentDictionary.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// ConcurrentDictionary.swift
//
//
// Created by Javier de Martín Gil on 16/2/22.
//
final class ConcurrentDictionary<K: Hashable,T>: Collection {
typealias Index = Dictionary<K, T>.Index
typealias Element = Dictionary<K, T>.Element
private var dictionary: [K: T]
private let concurrentQueue = DispatchQueue(label: "com.example.thread_safe_dictionary", attributes: .concurrent)
var startIndex: Index {
concurrentQueue.sync {
return self.dictionary.startIndex
}
}
var endIndex: Index {
concurrentQueue.sync {
return self.dictionary.startIndex
}
}
init(dictionary: Dictionary<K,T> = .init()) {
self.dictionary = dictionary
}
subscript(key: K) -> T? {
set {
self.concurrentQueue.async(flags: .barrier) {
self.dictionary[key] = newValue
}
}
get {
self.concurrentQueue.sync {
return self.dictionary[key]
}
}
}
subscript(index: Index) -> Element {
self.concurrentQueue.sync {
return self.dictionary[index]
}
}
func index(after i: Index) -> Index {
self.concurrentQueue.sync {
self.dictionary.index(after: i)
}
}
func removeValue(forKey key: K) {
self.concurrentQueue.async(flags: .barrier) {
self.dictionary.removeValue(forKey: key)
}
}
func removeAll() {
self.concurrentQueue.async(flags: .barrier) {
self.dictionary.removeAll()
}
}
}