Sync
We want to make a counter which is safe to use concurrently.
We'll start with an unsafe counter and verify its behaviour works in a single-threaded environment.
Then we'll exercise it's unsafeness with multiple goroutines trying to use it via a test and fix it.
We want our API to give us a method to increment the counter and then retrieve its value.
func TestCounter(t *testing.T) {
t.Run("incrementing the counter 3 times leaves it at 3", func(t *testing.T) {
counter := Counter{}
counter.Inc()
counter.Inc()
counter.Inc()
if counter.Value() != 3 {
t.Errorf("got %d, want %d", counter.Value(), 3)
}
})
}
./sync_test.go:9:14: undefined: Counter
Let's define
Counter
.type Counter struct {
}
Try again and it fails with the following
./sync_test.go:14:10: counter.Inc undefined (type Counter has no field or method Inc)
./sync_test.go:18:13: counter.Value undefined (type Counter has no field or method Value)
So to finally make the test run we can define those methods
func (c *Counter) Inc() {
}