In the previous example, we saw how to manage simple counter state using atomic operations. For more complex state, we can use a mutex to safely access data across multiple threads.
In this Objective-C version, we define a Container class that holds a mutable dictionary of counters. We use an NSLock to synchronize access to the counters.
The incrementForName: method locks the mutex before accessing the counters, and unlocks it at the end of the method.
In the main function, we create a Container instance and use Grand Central Dispatch (GCD) to run several blocks concurrently. Each block calls the doIncrement function, which increments a named counter in a loop.
We use a dispatch group to wait for all the blocks to finish before printing the final counter values.
To run the program, save it as Mutexes.m and compile it with:
Then run it:
The output shows that the counters were updated as expected, demonstrating that the mutex successfully protected the shared state from race conditions.
Next, we’ll look at implementing this same state management task using only blocks and dispatch queues.