Add NewBool

This commit is contained in:
Tevin Zhang 2016-05-25 15:06:49 +08:00
parent 6e6b80cf11
commit bb33e2abb1
2 changed files with 25 additions and 2 deletions

11
bool.go
View File

@ -4,11 +4,20 @@ package abool
import "sync/atomic" import "sync/atomic"
// New creates a pointer to an AtomicBool // New creates an AtomicBool with default to false
func New() *AtomicBool { func New() *AtomicBool {
return new(AtomicBool) return new(AtomicBool)
} }
// NewBool creates an AtomicBool with given default value
func NewBool(ok bool) *AtomicBool {
ab := New()
if ok {
ab.Set()
}
return ab
}
// AtomicBool is a atomic boolean // AtomicBool is a atomic boolean
// Note: When embedding into a struct, one should always use // Note: When embedding into a struct, one should always use
// *AtomicBool to avoid copy // *AtomicBool to avoid copy

View File

@ -7,7 +7,17 @@ import (
) )
func TestBool(t *testing.T) { func TestBool(t *testing.T) {
v := New() v := NewBool(true)
if !v.IsSet() {
t.Fatal("NewValue(true) failed")
}
v = NewBool(false)
if v.IsSet() {
t.Fatal("NewValue(false) failed")
}
v = New()
if v.IsSet() { if v.IsSet() {
t.Fatal("Empty value of AtomicBool should be false") t.Fatal("Empty value of AtomicBool should be false")
} }
@ -38,6 +48,8 @@ func TestRace(t *testing.T) {
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(repeat * 3) wg.Add(repeat * 3)
v := New() v := New()
// Writer
go func() { go func() {
for i := 0; i < repeat; i++ { for i := 0; i < repeat; i++ {
v.Set() v.Set()
@ -45,6 +57,7 @@ func TestRace(t *testing.T) {
} }
}() }()
// Reader
go func() { go func() {
for i := 0; i < repeat; i++ { for i := 0; i < repeat; i++ {
v.IsSet() v.IsSet()
@ -52,6 +65,7 @@ func TestRace(t *testing.T) {
} }
}() }()
// Writer
go func() { go func() {
for i := 0; i < repeat; i++ { for i := 0; i < repeat; i++ {
v.UnSet() v.UnSet()