GGMutableDictionary: Thread Safe NSMutableDictionary

According to Apple’s notes, the NSMutableDictionary is not safe if it is accessed from multiple threads simultaneously. To tackle this problem, one may choose to use a lock or a serial queue to synchronise access to a NSMutableDictionary. However, these approaches are pretty inefficient, especially in situations where reads happen much more often then writes. If a NSMutableDictionary is not being modified for a period of time, threads are free to access that dictionary simultaneously during that time interval. Following this logic, we can use dispatch_barrier_async and dispatch_sync operations on a parallel queue to implement a much more efficient multi-thread safe NSMutableDictionary.

The idea is to let multiple readers in different threads use dispatch_sync on a parallel queue, so they can access a NSMutableDictionary simultaneously. Then, when they would like to change the NSMutableDictionary, let them act as if there is only one writer writing to the dictionary. This is achieved by using dispatch_barrier_async, which will wait for all previously scheduled readers’ dispatch_sync and the writer’s dispatch_barrier_async operations to finish before executing itself. Also, operations scheduled after a dispatch_barrier_async operation will wait for the barrier operation to finish before executing. For more details, refer to the One Resource, Multiple Readers, and a Single Writer section of this article.

The following is my implementation. I name it GGMutableDictionary.