Failing concurrent test

pull/1/head
Drew Bednar 4 months ago
parent 6eb1756aa5
commit 77a1027ab0

@ -0,0 +1,3 @@
module my_sync
go 1.23.1

@ -0,0 +1,13 @@
package my_sync
type Counter struct {
count int
}
func (c *Counter) Inc() {
c.count++
}
func (c *Counter) Value() int {
return c.count
}

@ -0,0 +1,44 @@
package my_sync
import (
"sync"
"testing"
)
func assertCount(t testing.TB, got Counter, want int) {
t.Helper()
if got.Value() != want {
t.Errorf("got %d, want %d", got.Value(), want)
}
}
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()
assertCount(t, counter, 3)
})
t.Run("it runs safely concurrently", func(t *testing.T) {
wantedCount := 1000
counter := Counter{}
var wg sync.WaitGroup
wg.Add(wantedCount)
for i := 0; i < wantedCount; i++ {
go func() {
counter.Inc()
wg.Done()
}()
}
// blocking call to wait for all goroutines
wg.Wait()
assertCount(t, counter, wantedCount)
})
}
Loading…
Cancel
Save