forked from mirror/abool
Add NewBool
This commit is contained in:
parent
6e6b80cf11
commit
bb33e2abb1
11
bool.go
11
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
|
||||
|
|
16
bool_test.go
16
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()
|
||||
|
|
Loading…
Reference in New Issue