counter: Use a constructor
This commit is contained in:
parent
6ded953ec6
commit
436bcad0e1
@ -7,6 +7,10 @@ type Counter struct {
|
||||
mutex sync.Mutex
|
||||
}
|
||||
|
||||
func NewCounter() *Counter {
|
||||
return &Counter{}
|
||||
}
|
||||
|
||||
func (c *Counter) Inc() {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
@ -16,18 +16,18 @@ func assertCounter(t testing.TB, got *Counter, want int) {
|
||||
|
||||
func TestCounter(t *testing.T) {
|
||||
t.Run("incrementing the counter 3 times leaves it at 3", func(t *testing.T) {
|
||||
counter := Counter{}
|
||||
counter := NewCounter()
|
||||
|
||||
counter.Inc()
|
||||
counter.Inc()
|
||||
counter.Inc()
|
||||
|
||||
assertCounter(t, &counter, 3)
|
||||
assertCounter(t, counter, 3)
|
||||
})
|
||||
|
||||
t.Run("it runs safely concurrently", func(t *testing.T) {
|
||||
wantedCount := 1000
|
||||
counter := Counter{}
|
||||
counter := NewCounter()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(wantedCount)
|
||||
@ -39,6 +39,6 @@ func TestCounter(t *testing.T) {
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
assertCounter(t, &counter, wantedCount)
|
||||
assertCounter(t, counter, wantedCount)
|
||||
})
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user