Waitgroups in Ada
Our example demonstrates how to wait for multiple tasks to finish using a Protected_Counter
. This is similar to the concept of wait groups in other languages.
This is the equivalent of the worker function in Ada. It’s implemented as a task type.
The Protected_Counter
type is used to safely manage the count of active workers. It provides thread-safe operations to increment, decrement, and wait for the count to reach zero.
In the main procedure:
We create an array of Worker tasks and start them, incrementing the counter for each.
We then wait for all workers to finish by calling Counter.Wait
. This will block until all workers have decremented the counter.
Note that Ada’s tasking model inherently handles the termination of all tasks before the main program exits, so we don’t need to explicitly wait for task completion beyond this point.
To run the program, save it as waitgroups.adb
and use the following commands:
The order of workers starting up and finishing is likely to be different for each invocation.
Ada’s tasking model provides built-in support for concurrent programming, making it well-suited for this kind of parallel execution pattern. The Protected_Counter
type ensures thread-safe operations, similar to the sync.WaitGroup
in other languages.