Mutex, WaitGroup, Once

When state is shared, it is covered by a lock. A mutex must not be copied.

A mutex protects data, not "a piece of code in general". It should lie next to the fields it guards:

type Counter struct {
    mu sync.Mutex
    n  int
}

func (c *Counter) Inc() int {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.n++
    return c.n
}

defer Unlock keeps you from forgetting to release on an early return. The method receiver is a pointer. If the receiver is by value, the method locks a copy of the mutex, and the other calls look at a different one. Copying a struct that contains a mutex after the first use is also a mistake: two copies do not protect the same data. go vet often notices this.

RWMutex lets many readers through, or one writer. It pays off when reads are noticeably more frequent and they are not instantaneous. For a counter an ordinary Mutex is simpler and more honest.

WaitGroup waits for a set of goroutines. Add is called before the goroutine starts, not inside it: otherwise Wait can slip through before Add. Done is placed with defer at the start of the goroutine.

sync.Once runs a function exactly once, even under simultaneous calls. It is used to initialize a lazy resource. Once cannot "reset and do it again". It does not fit repeated initialization.

sync/atomic belongs on a single counter or flag, where a mutex would be heavier than the thought. As soon as more than one field is under protection, take a mutex: atomic operations are easy to assemble into a sequence that is not atomic.

Practice

  1. A copy of a mutex

    The method Inc is declared on the value Counter, which contains a sync.Mutex. What does it lock?

    • The shared mutex of every Counter in the process
    • A copy of the mutex, which no longer protects anyone else
    • The mutex of the package sync
    • Nothing. A value receiver with a mutex does not compile
  2. When to call Add

    When do you increment a WaitGroup if you need to wait for a goroutine?

    • Inside the goroutine, on the first line
    • Before go, in the function that starts it
    • After Wait
    • In the package init, once for every goroutine of the program
  3. How many times Once runs

    Ten goroutines called the same sync.Once with one function at the same time. How many times will that function run? Write a number.