From bb33e2abb1a0b138740d41dd5924397fb08e9822 Mon Sep 17 00:00:00 2001 From: Tevin Zhang Date: Wed, 25 May 2016 15:06:49 +0800 Subject: [PATCH] Add NewBool --- bool.go | 11 ++++++++++- bool_test.go | 16 +++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) 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()