Our example demonstrates state management using tasks (Ada’s equivalent to goroutines) and protected objects for synchronization. This approach aligns with Ada’s built-in concurrency features and the principle of sharing data through communication.
In this Ada example, we use a protected object State_Manager to manage the shared state. This ensures that the data is never corrupted with concurrent access. The Read and Write procedures of the protected object encapsulate the requests to read or write the state.
We create 100 reader tasks and 10 writer tasks. Each task performs operations in a loop, using Ada’s random number generation to select keys and values. The System.Atomic_Counters package is used to safely count the number of operations performed.
The main procedure lets the tasks run for one second, then reports the number of read and write operations performed.
To run the program, save it as stateful_tasks.adb and use the following commands:
Running this program will show the number of read and write operations completed in one second. The exact numbers will vary, but you might see output similar to this:
This Ada implementation demonstrates state management using tasks and protected objects, which are Ada’s built-in mechanisms for concurrent programming. While the approach is different from Go’s goroutines and channels, it achieves the same goal of safe concurrent access to shared state.