diff --git a/Tusker/Caching/DiskCache.swift b/Tusker/Caching/DiskCache.swift index e702728b..9420ae15 100644 --- a/Tusker/Caching/DiskCache.swift +++ b/Tusker/Caching/DiskCache.swift @@ -21,7 +21,7 @@ class DiskCache { let defaultExpiry: CacheExpiry let transformer: DiskCacheTransformer - private var fileStates = [String: FileState]() + private var fileStates = MultiThreadDictionary() init(name: String, defaultExpiry: CacheExpiry, transformer: DiskCacheTransformer, fileManager: FileManager = .default) throws { self.defaultExpiry = defaultExpiry @@ -117,7 +117,9 @@ class DiskCache { func removeAll() throws { try fileManager.removeItem(atPath: path) try createDirectory() - fileStates.removeAll() + fileStates.withLock { dict in + dict.removeAll() + } } } diff --git a/Tusker/MultiThreadDictionary.swift b/Tusker/MultiThreadDictionary.swift index fd8cd206..26392bb5 100644 --- a/Tusker/MultiThreadDictionary.swift +++ b/Tusker/MultiThreadDictionary.swift @@ -16,13 +16,7 @@ class MultiThreadDictionary { private let lock: LockHolder<[AnyHashable: Any]> init() { - if #available(iOS 16.0, *) { - let lock = OSAllocatedUnfairLock(initialState: [:]) - self.lock = LockHolder(withLock: lock.withLock(_:)) - } else { - let lock = UnfairLock(initialState: [:]) - self.lock = LockHolder(withLock: lock.withLock(_:)) - } + self.lock = LockHolder(initialState: [:]) } subscript(key: Key) -> Value? { @@ -66,6 +60,16 @@ class MultiThreadDictionary { // see #178 fileprivate struct LockHolder { let withLock: (_ body: @Sendable (inout State) throws -> any Sendable) throws -> any Sendable + + init(initialState: State) { + if #available(iOS 16.0, *) { + let lock = OSAllocatedUnfairLock(initialState: initialState) + self.withLock = lock.withLock(_:) + } else { + let lock = UnfairLock(initialState: initialState) + self.withLock = lock.withLock(_:) + } + } } // TODO: replace this only with OSAllocatedUnfairLock