don't embed the mutex (#400)
Do not embed the mutex in the mutex example
This commit is contained in:
parent
35ad9cc35c
commit
2621c73d29
@ -12,29 +12,28 @@ import (
|
|||||||
|
|
||||||
// Container holds a map of counters; since we want to
|
// Container holds a map of counters; since we want to
|
||||||
// update it concurrently from multiple goroutines, we
|
// update it concurrently from multiple goroutines, we
|
||||||
// add a `Mutex` to synchronize access. The mutex is
|
// add a `Mutex` to synchronize access.
|
||||||
// _embedded_ in this `struct`; this is idiomatic in Go.
|
|
||||||
// Note that mutexes must not be copied, so if this
|
// Note that mutexes must not be copied, so if this
|
||||||
// `struct` is passed around, it should be done by
|
// `struct` is passed around, it should be done by
|
||||||
// pointer.
|
// pointer.
|
||||||
type Container struct {
|
type Container struct {
|
||||||
sync.Mutex
|
mu sync.Mutex
|
||||||
counters map[string]int
|
counters map[string]int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Container) inc(name string) {
|
func (c *Container) inc(name string) {
|
||||||
// Lock the mutex before accessing `counters`; unlock
|
// Lock the mutex before accessing `counters`; unlock
|
||||||
// it at the end of the function using a [defer](defer)
|
// it at the end of the function using a [defer](defer)
|
||||||
// statement. Since the mutex is embedded into
|
// statement.
|
||||||
// `Container`, we can call the mutex's methods like
|
c.mu.Lock()
|
||||||
// `Lock` directly on `c`.
|
defer c.mu.Unlock()
|
||||||
c.Lock()
|
|
||||||
defer c.Unlock()
|
|
||||||
c.counters[name]++
|
c.counters[name]++
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
c := Container{
|
c := Container{
|
||||||
|
// Note that the zero value of a mutex is usable as-is, so no
|
||||||
|
// initialization is required here.
|
||||||
counters: map[string]int{"a": 0, "b": 0},
|
counters: map[string]int{"a": 0, "b": 0},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user