Writing Thread-Safe Classes with GCD
September 13, 2014
This is the fifth post in a series about Grand Central Dispatch.
So far, we’ve learned that a multi-threaded program means that access to our data structures must be protected by some kind of synchronization mechanism. We used GCD’s serial queues to gate access to our data structures.
We also discussed using concurrent queues to implement a Readers-Writer lock. To keep this post simple, we’ll stick to using serial queues.
One serious issue remains: whoever uses your data structures have to remember to use
dispatch_sync(), otherwise you get errors. This is obviously a problem, especially when your code is used by someone not familiar with your arrangement (for instance, when your code is part of a framework).
Wouldn’t it be great if we could encapsulate the synchronization behavior into our data structure, so that its users don’t have to worry about asynchronous behavior?
Encapsulation, of course, is what classes are really good for. Instead of requiring synchronization code in our user’s codebase, we should make thread-safe classes.