DeviceCache has mechanisms for thread safety, and many objects that have a reference to the DeviceCache also control access internally, however, if you have multiple objects each on different threads reading and then writing data, there might be times when a race condition can develop. DeviceCache uses a queue to add safety. However, there is nothing stopping a situation like:
Thread 1 reads data from cache
Thread 2 reads data from cache
Thread 1 writes data back to cache
Thread 2 writes stale data back to cache overwriting changes
Most places where we manipulate the cache, we rely on the objects utilizing the cache to control access by:
- locking
- reading
- writing
- unlocking
However, because no objects share locks, we can still get into this race condition situation because the Device Cache is ready to service read/write requests from a different thread as soon as 2. happens.
How to fix?
Maybe something like how CoreData manages this type of situation? The ManagedObjectContext has a perform function that executes a block of code in the context's queue. If we were to do something like that, we could ensure steps 1 through 4 all happened atomically.
This would change the API so that device cache looked more like:
deviceCache.perform { cache in
let someValues = cache.read()
...
cache.write(modifiedValues)
}
DeviceCache has mechanisms for thread safety, and many objects that have a reference to the DeviceCache also control access internally, however, if you have multiple objects each on different threads reading and then writing data, there might be times when a race condition can develop. DeviceCache uses a queue to add safety. However, there is nothing stopping a situation like:
Thread 1 reads data from cache
Thread 2 reads data from cache
Thread 1 writes data back to cache
Thread 2 writes stale data back to cache overwriting changes
Most places where we manipulate the cache, we rely on the objects utilizing the cache to control access by:
However, because no objects share locks, we can still get into this race condition situation because the Device Cache is ready to service read/write requests from a different thread as soon as
2.happens.How to fix?
Maybe something like how
CoreDatamanages this type of situation? TheManagedObjectContexthas aperformfunction that executes a block of code in the context's queue. If we were to do something like that, we could ensure steps1through4all happened atomically.This would change the API so that device cache looked more like: