sync.Mutex

We've seen how channels are great for communication among goroutines.

But what if we don't need communication? What if we just want to make sure only one goroutine can access a variable at a time to avoid conflicts?

This concept is called mutual exclusion, and the conventional name for the data structure that provides it is mutex.

Go's standard library provides mutual exclusion with sync.Mutex and its two methods:

  • Lock
  • Unlock

    We can define a block of code to be executed in mutual exclusion by surrounding it with a call to Lock and Unlock as shown on the Inc method.

    We can also use defer to ensure the mutex will be unlocked as in the Value method.

mutex-counter.go

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. // SafeCounter is safe to use concurrently.
  8. type SafeCounter struct {
  9. v map[string]int
  10. mux sync.Mutex
  11. }
  12. // Inc increments the counter for the given key.
  13. func (c *SafeCounter) Inc(key string) {
  14. c.mux.Lock()
  15. // Lock so only one goroutine at a time can access the map c.v.
  16. c.v[key]++
  17. c.mux.Unlock()
  18. }
  19. // Value returns the current value of the counter for the given key.
  20. func (c *SafeCounter) Value(key string) int {
  21. c.mux.Lock()
  22. // Lock so only one goroutine at a time can access the map c.v.
  23. defer c.mux.Unlock()
  24. return c.v[key]
  25. }
  26. func main() {
  27. c := SafeCounter{v: make(map[string]int)}
  28. for i := 0; i < 1000; i++ {
  29. go c.Inc("somekey")
  30. }
  31. time.Sleep(time.Second)
  32. fmt.Println(c.Value("somekey"))
  33. }