cache coherency protocol is well known in multi-cores context which is in the hardware low-level, however, we will meet the similar case in the application domain. Recently, I am working on a project which has two threads updating shared objects.
- UI thread is responsible for displaying and updating(via users action) objects.
- Background replication thread periodically updates the shared objects if something is changed by other users.
since we have lots of objects(50,000~100,000), each thread have to copy part of objects into its own buffer, updating the shared objects is serial.
- UI thread will not update object each time when users update.
- Back开发者_开发技巧ground replication thread will update objects immediately once changes are found and then notify UI thread to refresh.
So this brings the question, if there is a object updated by two threads, how is conflict sovled? Is there any common idiom to handle this case?
The simplest way to handle this is to use a mutex. The UI locks the mutex before it reads the value, then unlocks it afterwards. The background thread locks the mutex before it updates the value, then unlocks it afterwards.
You can have the update thread send a notification message to the UI telling it to reread the shared object, as you suggested.
精彩评论