diff --git a/bool.go b/bool.go index 8d86be3..3921a53 100644 --- a/bool.go +++ b/bool.go @@ -4,11 +4,20 @@ package abool import "sync/atomic" -// New creates a pointer to an AtomicBool +// New creates an AtomicBool with default to false func 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 // Note: When embedding into a struct, one should always use // *AtomicBool to avoid copy diff --git a/bool_test.go b/bool_test.go index 060fe3b..81fd636 100644 --- a/bool_test.go +++ b/bool_test.go @@ -7,7 +7,17 @@ import ( ) 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() { t.Fatal("Empty value of AtomicBool should be false") } @@ -38,6 +48,8 @@ func TestRace(t *testing.T) { var wg sync.WaitGroup wg.Add(repeat * 3) v := New() + + // Writer go func() { for i := 0; i < repeat; i++ { v.Set() @@ -45,6 +57,7 @@ func TestRace(t *testing.T) { } }() + // Reader go func() { for i := 0; i < repeat; i++ { v.IsSet() @@ -52,6 +65,7 @@ func TestRace(t *testing.T) { } }() + // Writer go func() { for i := 0; i < repeat; i++ { v.UnSet()