Mutexes
package main
import (
"fmt"
"sync"
)
// Container represents a structure with a mutex-protected map of counters.
type Container struct {
mu sync.Mutex
counters map[string]int
}
// inc increments the counter for a given name, protected by a mutex.
func (c *Container) inc(name string) {
c.mu.Lock()
defer c.mu.Unlock()
c.counters[name]++
}
func main() {
// Initializing a Container with counters for names "a" and "b"
c := Container{
counters: map[string]int{"a": 0, "b": 0},
}
var wg sync.WaitGroup
// doIncrement is a function that increments a counter 'n' times for a given name.
doIncrement := func(name string, n int) {
for i := 0; i < n; i++ {
c.inc(name)
}
wg.Done()
}
// Launching three goroutines to increment counters concurrently.
wg.Add(3)
go doIncrement("a", 10000)
go doIncrement("a", 10000)
go doIncrement("b", 10000)
// Waiting for all goroutines to finish.
wg.Wait()
// Printing the final counters.
fmt.Println(c.counters)
}Output
Last updated