-
Notifications
You must be signed in to change notification settings - Fork 8
/
ThreadSafeDictionary.swift
81 lines (69 loc) · 2.07 KB
/
ThreadSafeDictionary.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
72
73
74
75
76
77
78
79
80
81
//
// ThreadSafeDictionary.swift
//
// Created by Shashank on 29/10/20.
//
class ThreadSafeDictionary<V: Hashable,T>: Collection {
private var dictionary: [V: T]
private let concurrentQueue = DispatchQueue(label: "Dictionary Barrier Queue",
attributes: .concurrent)
var keys: Dictionary<V, T>.Keys {
self.concurrentQueue.sync {
return self.dictionary.keys
}
}
var values: Dictionary<V, T>.Values {
self.concurrentQueue.sync {
return self.dictionary.values
}
}
var startIndex: Dictionary<V, T>.Index {
self.concurrentQueue.sync {
return self.dictionary.startIndex
}
}
var endIndex: Dictionary<V, T>.Index {
self.concurrentQueue.sync {
return self.dictionary.endIndex
}
}
init(dict: [V: T] = [V:T]()) {
self.dictionary = dict
}
// this is because it is an apple protocol method
// swiftlint:disable identifier_name
func index(after i: Dictionary<V, T>.Index) -> Dictionary<V, T>.Index {
self.concurrentQueue.sync {
return self.dictionary.index(after: i)
}
}
// swiftlint:enable identifier_name
subscript(key: V) -> T? {
set(newValue) {
self.concurrentQueue.async(flags: .barrier) {[weak self] in
self?.dictionary[key] = newValue
}
}
get {
self.concurrentQueue.sync {
return self.dictionary[key]
}
}
}
// has implicity get
subscript(index: Dictionary<V, T>.Index) -> Dictionary<V, T>.Element {
self.concurrentQueue.sync {
return self.dictionary[index]
}
}
func removeValue(forKey key: V) {
self.concurrentQueue.async(flags: .barrier) {[weak self] in
self?.dictionary.removeValue(forKey: key)
}
}
func removeAll() {
self.concurrentQueue.async(flags: .barrier) {[weak self] in
self?.dictionary.removeAll()
}
}
}