mirror of
https://github.com/qvacua/vimr.git
synced 2024-09-11 17:15:34 +03:00
Use Dispatch
This commit is contained in:
parent
6ab66b9045
commit
a0ec21db29
@ -15,45 +15,22 @@ public final class FifoCache<Key: Hashable, Value> {
|
||||
}
|
||||
|
||||
public func set(_ value: Value, forKey key: Key) {
|
||||
self.lock.lock()
|
||||
defer { self.lock.unlock() }
|
||||
self.queue.sync {
|
||||
self.keyWriteIndex = (self.keyWriteIndex + 1) % self.count
|
||||
|
||||
self.keyWriteIndex = (self.keyWriteIndex + 1) % self.count
|
||||
if let keyToDel = self.keys[self.keyWriteIndex] { self.storage.removeValue(forKey: keyToDel) }
|
||||
|
||||
if let keyToDel = self.keys[self.keyWriteIndex] { self.storage.removeValue(forKey: keyToDel) }
|
||||
|
||||
self.keys[self.keyWriteIndex] = key
|
||||
self.storage[key] = value
|
||||
self.keys[self.keyWriteIndex] = key
|
||||
self.storage[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
public func valueForKey(_ key: Key) -> Value? { self.lock.withLock { self.storage[key] } }
|
||||
public func valueForKey(_ key: Key) -> Value? { self.queue.sync { self.storage[key] } }
|
||||
|
||||
private let count: Int
|
||||
private var keys: Array<Key?>
|
||||
private var keyWriteIndex: Int
|
||||
private var storage: Dictionary<Key, Value>
|
||||
|
||||
private let lock = Lock()
|
||||
}
|
||||
|
||||
fileprivate final class Lock {
|
||||
|
||||
init() { pthread_mutex_init(self.mutex, nil) }
|
||||
|
||||
deinit {
|
||||
pthread_mutex_destroy(self.mutex)
|
||||
self.mutex.deallocate()
|
||||
}
|
||||
|
||||
func lock() { pthread_mutex_lock(self.mutex) }
|
||||
|
||||
func unlock() { pthread_mutex_unlock(self.mutex) }
|
||||
|
||||
func withLock<T>(_ body: () -> T) -> T {
|
||||
self.lock()
|
||||
defer { self.unlock() }
|
||||
return body()
|
||||
}
|
||||
|
||||
private let mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
|
||||
private let queue = DispatchQueue(label: "FifoCache-\(UUID().uuidString)", qos: .userInteractive)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user