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.
Running the program shows that the counters updated as expected.
In this Julia version:
We use ReentrantLock from Base.Threads instead of sync.Mutex.
The Container struct is defined as mutable to allow modification of its fields.
The inc! function uses a do block with lock to ensure thread safety.
We use @spawn to create concurrent tasks instead of goroutines.
@sync is used to wait for all spawned tasks to complete, similar to WaitGroup in Go.
Julia’s Dict is used instead of Go’s map.
This example demonstrates how to use mutexes in Julia to safely manage state across multiple concurrent tasks.
Next, we’ll look at implementing this same state management task using only tasks and channels.