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.
Next we’ll look at implementing this same state management task using only threads and queues.
This Ruby code demonstrates the use of mutexes to safely manage shared state across multiple threads. Here are some key points:
We use the Mutex class from Ruby’s thread library to create a mutex.
The Container class encapsulates the shared state (a hash of counters) and the mutex.
The inc method uses @mu.synchronize to ensure that only one thread can access the counters at a time.
We create multiple threads that concurrently increment the counters.
We use Thread.new to create new threads and thread.join to wait for them to finish.
This approach ensures that our counter increments are thread-safe, preventing race conditions that could occur with unsynchronized access to shared state.