Thread safety #63
Replies: 1 comment 1 reply
-
Locks definitely work and there's no reason to not use them. You can also hold onto an actor under the hood of the dependency and use that for synchronization. Note that you generally do not want to make the dependency itself an actor, but you can still use one for the live implementation. However, the are some problems with your dependency as you have demonstrated it above. You shouldn't think of the cache itself as the dependency, but rather access to the cache as the dependency. That way you can lock the beginning-to-end process of accessing the cache and grabbing a value. Right now you are only locking the access to the cache, but not fetching/setting data. One way to do this is to design a client with struct CacheClient {
var get: (String) -> Image
var set: (String, Image) -> Void
}
extension CacheClient: DependencyKey {
static var liveValue: CacheClient {
let lock = NSLock()
let cache = Cache<RemoteImageResource>(maxSize: 100)
return Self(
get: { key in lock.withCriticalSection { cache.get(key) } },
set: { key, image in lock.withCriticalSection { cache.set(key, image) } }
)
}
} |
Beta Was this translation helpful? Give feedback.
-
Is this the recommended way (or one of the recommended ways) for making dependencies thread safe?
Beta Was this translation helpful? Give feedback.
All reactions