In the previous example, we saw how to manage simple counter state using atomic operations. For more complex state, we can use a lock to safely access data across multiple tasks.
Running the program shows that the counters updated as expected.
In this Chapel version:
We use a sync variable counterLock instead of a mutex to provide synchronization.
The Container class holds the lock and the map of counters.
The inc method uses the sync variable to provide mutual exclusion.
We use Chapel’s begin statement to spawn concurrent tasks, similar to goroutines in Go.
The sync block in main is used to wait for all tasks to complete, similar to WaitGroup in Go.
Chapel’s map type is used instead of Go’s map.
This example demonstrates how to use synchronization primitives in Chapel to safely manage shared state across multiple concurrent tasks.