Skip to content

Commit

Permalink
Merge pull request #16 from neftales/sync
Browse files Browse the repository at this point in the history
Sync chapter
  • Loading branch information
neftales authored Jun 2, 2024
2 parents e8138bc + 25363a1 commit 6e96dd6
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
23 changes: 23 additions & 0 deletions sync/sync.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package sync

import "sync"

type Counter struct {
mutex sync.Mutex
value int
}

func NewCounter() *Counter {
return &Counter{}
}

func (c *Counter) Inc() {
c.mutex.Lock()
defer c.mutex.Unlock()

c.value++
}

func (c *Counter) Value() int {
return c.value
}
44 changes: 44 additions & 0 deletions sync/sync_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package sync

import (
"sync"
"testing"
)

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)
})
}

func assertCounter(t testing.TB, got *Counter, want int) {
t.Helper()

if got.Value() != want {
t.Errorf("got %d, want %d", got.Value(), want)
}
}

0 comments on commit 6e96dd6

Please sign in to comment.