Mutexes
This Go code illustrates the use of a mutex (Mutual Exclusion) to safely increment counters in a concurrent environment. Here's an explanation with inline comments:
Output
Explanation:
Container
struct: It includes a mutex (mu
) and a map of counters (counters
).inc
method: It increments the counter for a given name, using a mutex (mu
) to protect concurrent access.In the
main
function:An instance of
Container
(c
) is created with counters initialized for names "a" and "b".The
doIncrement
function is defined to increment a counter 'n' times for a given name. It usesc.inc
to safely increment counters.Three goroutines are launched concurrently to increment counters for names "a" and "b".
The
sync.WaitGroup
(wg
) is used to wait for all goroutines to finish before proceeding.The final counters are printed.
Using a mutex ensures that the inc
method is executed atomically, preventing race conditions that might occur when multiple goroutines attempt to modify the counters concurrently. This approach ensures the correctness and safety of the concurrent counter increments.
Last updated
Was this helpful?