Skip to content

Commit

Permalink
Merge pull request #15 from jolestar/ci-debug
Browse files Browse the repository at this point in the history
fix atomic race condition bug.
  • Loading branch information
jolestar authored Oct 31, 2016
2 parents 96f4565 + 35a9291 commit 90e2a2c
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ language: go
sudo: false
go:
- 1.4
- 1.6
- 1.7
- tip
install:
- go get github.com/stretchr/testify
Expand Down
8 changes: 4 additions & 4 deletions concurrent/atomic.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func (i *AtomicInteger) IncrementAndGet() int32 {

// GetAndIncrement increment wrapped int32 with 1 and return old value.
func (i *AtomicInteger) GetAndIncrement() int32 {
ret := int32(*i)
ret := atomic.LoadInt32((*int32)(i))
atomic.AddInt32((*int32)(i), int32(1))
return ret
}
Expand All @@ -24,12 +24,12 @@ func (i *AtomicInteger) DecrementAndGet() int32 {

// GetAndDecrement decrement wrapped int32 with 1 and return old value.
func (i *AtomicInteger) GetAndDecrement() int32 {
ret := int32(*i)
ret := atomic.LoadInt32((*int32)(i))
atomic.AddInt32((*int32)(i), int32(-1))
return ret
}

// Get current value
func (i AtomicInteger) Get() int32 {
return int32(i)
func (i *AtomicInteger) Get() int32 {
return atomic.LoadInt32((*int32)(i))
}
27 changes: 26 additions & 1 deletion concurrent/atomic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func TestAtomicConcurrentDecrement(t *testing.T) {
assert.Equal(t, int32(0), integer.Get())
}

func TestAtomicConcurrentIncrementAndDecrement(t *testing.T) {
func TestAtomicConcurrentIncrementAndDecrementAndGet(t *testing.T) {
count := 100
integer := AtomicInteger(0)
wait := sync.WaitGroup{}
Expand All @@ -79,6 +79,31 @@ func TestAtomicConcurrentIncrementAndDecrement(t *testing.T) {
} else {
integer.DecrementAndGet()
}
integer.Get()
wait.Done()
}(i)
}
start.Done()
wait.Wait()
assert.Equal(t, int32(0), integer.Get())
}

func TestAtomicConcurrentGetAndIncrementAndDecrement(t *testing.T) {
count := 100
integer := AtomicInteger(0)
wait := sync.WaitGroup{}
wait.Add(count)
start := sync.WaitGroup{}
start.Add(1)
for i := 0; i < count; i++ {
go func(idx int) {
start.Wait()
if idx%2 == 0 {
integer.GetAndIncrement()
} else {
integer.GetAndDecrement()
}
integer.Get()
wait.Done()
}(i)
}
Expand Down

0 comments on commit 90e2a2c

Please sign in to comment.