From 3b5410404cebe8cc4c201cc6f925246462b5bcc8 Mon Sep 17 00:00:00 2001 From: jolestar Date: Mon, 31 Oct 2016 16:23:48 +0800 Subject: [PATCH 1/2] fix atomic race condition bug. --- concurrent/atomic.go | 8 ++++---- concurrent/atomic_test.go | 27 ++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/concurrent/atomic.go b/concurrent/atomic.go index c329950..57b7fde 100644 --- a/concurrent/atomic.go +++ b/concurrent/atomic.go @@ -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 } @@ -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)) } diff --git a/concurrent/atomic_test.go b/concurrent/atomic_test.go index 625a5c0..6542a0a 100644 --- a/concurrent/atomic_test.go +++ b/concurrent/atomic_test.go @@ -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{} @@ -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) } From 35a9291bee48b83ef9bf1d29bdbe8977a55f641f Mon Sep 17 00:00:00 2001 From: jolestar Date: Mon, 31 Oct 2016 16:24:27 +0800 Subject: [PATCH 2/2] support more version. --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index 1a988e5..3f62914 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,8 @@ language: go sudo: false go: - 1.4 +- 1.6 +- 1.7 - tip install: - go get github.com/stretchr/testify