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 tasks.
This Ada program demonstrates the use of a protected type, which is Ada’s equivalent to a mutex. The Container type uses a protected type to ensure thread-safe access to its internal map.
The program creates three tasks that concurrently increment counters in the shared Container. Two tasks increment the “a” counter, and one task increments the “b” counter.
To run the program, save it as mutexes.adb and compile it with an Ada compiler:
Running the program shows that the counters are updated as expected, demonstrating safe concurrent access to shared state using Ada’s protected types.
Next, we’ll look at implementing this same state management task using only tasks and other synchronization primitives in Ada.