Compare commits
5 Commits
a0bad4d6e9
...
436bcad0e1
Author | SHA1 | Date | |
---|---|---|---|
436bcad0e1 | |||
6ded953ec6 | |||
572c8033f6 | |||
ea6f225992 | |||
41ae820a21 |
22
counter/counter.go
Normal file
22
counter/counter.go
Normal file
@ -0,0 +1,22 @@
|
||||
package counter
|
||||
|
||||
import "sync"
|
||||
|
||||
type Counter struct {
|
||||
count int
|
||||
mutex sync.Mutex
|
||||
}
|
||||
|
||||
func NewCounter() *Counter {
|
||||
return &Counter{}
|
||||
}
|
||||
|
||||
func (c *Counter) Inc() {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
c.count++
|
||||
}
|
||||
|
||||
func (c *Counter) Value() int {
|
||||
return c.count
|
||||
}
|
44
counter/counter_test.go
Normal file
44
counter/counter_test.go
Normal file
@ -0,0 +1,44 @@
|
||||
package counter
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// assertCounter
|
||||
// XXX: a copy of Counter is created, but we shouldn't copy a mutex. Use pointer instead.
|
||||
func assertCounter(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 := NewCounter()
|
||||
|
||||
counter.Inc()
|
||||
counter.Inc()
|
||||
counter.Inc()
|
||||
|
||||
assertCounter(t, counter, 3)
|
||||
})
|
||||
|
||||
t.Run("it runs safely concurrently", func(t *testing.T) {
|
||||
wantedCount := 1000
|
||||
counter := NewCounter()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(wantedCount)
|
||||
|
||||
for i := 0; i < wantedCount; i++ {
|
||||
go func() {
|
||||
counter.Inc()
|
||||
wg.Done()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
assertCounter(t, counter, wantedCount)
|
||||
})
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user