Skip to content

DeviceCache thread safety #739

Description

@taquitos

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:

  1. locking
  2. reading
  3. writing
  4. 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)
}

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions