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 threads.
Running the program shows that the counters updated as expected.
In this Cilk version, we’ve made several adaptations:
We use cilk_spawn to create parallel tasks instead of goroutines.
We use cilk_sync to wait for all spawned tasks to complete, similar to WaitGroup in Go.
We use C++ std::mutex and std::lock_guard for synchronization.
We use a C++ lambda function for doIncrement instead of a closure.
We use std::map instead of Go’s built-in map type.
The overall structure and logic remain the same, demonstrating how to safely access shared state across multiple threads using a mutex.
Next, we’ll look at implementing this same state management task using only threads and message passing.