counter: Use a constructor

This commit is contained in:
vinchent 2024-09-21 19:48:58 +02:00
parent 6ded953ec6
commit 436bcad0e1
2 changed files with 8 additions and 4 deletions

View File

@ -7,6 +7,10 @@ type Counter struct {
mutex sync.Mutex mutex sync.Mutex
} }
func NewCounter() *Counter {
return &Counter{}
}
func (c *Counter) Inc() { func (c *Counter) Inc() {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock() defer c.mutex.Unlock()

View File

@ -16,18 +16,18 @@ func assertCounter(t testing.TB, got *Counter, want int) {
func TestCounter(t *testing.T) { func TestCounter(t *testing.T) {
t.Run("incrementing the counter 3 times leaves it at 3", func(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() counter.Inc()
counter.Inc() counter.Inc()
assertCounter(t, &counter, 3) assertCounter(t, counter, 3)
}) })
t.Run("it runs safely concurrently", func(t *testing.T) { t.Run("it runs safely concurrently", func(t *testing.T) {
wantedCount := 1000 wantedCount := 1000
counter := Counter{} counter := NewCounter()
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(wantedCount) wg.Add(wantedCount)
@ -39,6 +39,6 @@ func TestCounter(t *testing.T) {
}() }()
} }
wg.Wait() wg.Wait()
assertCounter(t, &counter, wantedCount) assertCounter(t, counter, wantedCount)
}) })
} }