Add race test

This commit is contained in:
Tevin Zhang 2016-05-25 14:57:10 +08:00
parent ba4fdb7068
commit 6e6b80cf11
2 changed files with 37 additions and 9 deletions

18
bool.go
View File

@ -14,15 +14,6 @@ func New() *AtomicBool {
// *AtomicBool to avoid copy
type AtomicBool int32
// SetTo sets the boolean with given bool
func (ab *AtomicBool) SetTo(yes bool) {
if yes {
atomic.StoreInt32((*int32)(ab), 1)
} else {
atomic.StoreInt32((*int32)(ab), 0)
}
}
// Set sets the bool to true
func (ab *AtomicBool) Set() {
atomic.StoreInt32((*int32)(ab), 1)
@ -37,3 +28,12 @@ func (ab *AtomicBool) UnSet() {
func (ab *AtomicBool) IsSet() bool {
return atomic.LoadInt32((*int32)(ab)) == 1
}
// SetTo sets the boolean with given bool
func (ab *AtomicBool) SetTo(yes bool) {
if yes {
atomic.StoreInt32((*int32)(ab), 1)
} else {
atomic.StoreInt32((*int32)(ab), 0)
}
}

View File

@ -33,6 +33,34 @@ func TestBool(t *testing.T) {
}
}
func TestRace(t *testing.T) {
repeat := 10000
var wg sync.WaitGroup
wg.Add(repeat * 3)
v := New()
go func() {
for i := 0; i < repeat; i++ {
v.Set()
wg.Done()
}
}()
go func() {
for i := 0; i < repeat; i++ {
v.IsSet()
wg.Done()
}
}()
go func() {
for i := 0; i < repeat; i++ {
v.UnSet()
wg.Done()
}
}()
wg.Wait()
}
func ExampleAtomicBool() {
cond := New() // default to false
cond.Set() // set to true