In this example, we’ll explore how to use mutexes to safely access data across multiple threads. This is useful for managing more complex state than what can be handled with simple atomic operations.
This C program demonstrates the use of mutexes to safely manage concurrent access to shared data. Here’s a breakdown of the key components:
We define a Container struct that holds an array of counters and a mutex.
The container_init function initializes the mutex and counters.
The inc function increments a counter, using the mutex to ensure thread-safe access.
The doIncrement function runs in a separate thread, repeatedly calling inc.
In main, we create three threads that concurrently increment the counters.
After all threads complete, we print the final counter values.
To compile and run the program:
This output shows that the counters were updated as expected, with proper synchronization preventing race conditions.
Note that C doesn’t have built-in support for maps like Go does, so we’ve simplified the example to use an array instead. Also, C requires manual memory management and explicit thread creation/joining, which adds some complexity compared to the Go version.