Our example demonstrates how to manage state using a dedicated thread and message passing in Objective-C. This approach aligns with the idea of sharing memory by communicating and having each piece of data owned by exactly one thread.
In this Objective-C version, we use Grand Central Dispatch (GCD) to manage concurrency. The StateManager class encapsulates the state and provides methods to handle read and write operations. The state is accessed only on a dedicated serial queue to ensure thread safety.
We start 100 read operation threads and 10 write operation threads, each performing 1000 operations. The operations are executed asynchronously, and we use atomic increments to count the number of completed operations.
To run the program, compile it with the Objective-C compiler and execute the resulting binary:
Running our program shows that it completes about 80,000 total operations in one second:
This approach using a dedicated thread (via GCD’s serial queue) for state management is more involved than using locks, but it can be useful in certain cases. For example, when you have other asynchronous operations involved or when managing multiple locks would be error-prone. You should use whichever approach feels most natural, especially with respect to understanding the correctness of your program.