From cdaddb8a0ed41d9ddefeb80170b867a24b2de2d6 Mon Sep 17 00:00:00 2001 From: siddontang Date: Fri, 21 Nov 2014 09:53:23 +0800 Subject: [PATCH] add atomic bool --- sync2/atomic.go | 14 ++++++++++++++ sync2/atomic_test.go | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/sync2/atomic.go b/sync2/atomic.go index 394d780..1eb7dff 100644 --- a/sync2/atomic.go +++ b/sync2/atomic.go @@ -130,3 +130,17 @@ func (s *AtomicString) CompareAndSwap(oldval, newval string) (swqpped bool) { } return false } + +type AtomicBool int32 + +func (b *AtomicBool) Set(v bool) { + if v { + atomic.StoreInt32((*int32)(b), 1) + } else { + atomic.StoreInt32((*int32)(b), 0) + } +} + +func (b *AtomicBool) Get() bool { + return atomic.LoadInt32((*int32)(i)) == 1 +} diff --git a/sync2/atomic_test.go b/sync2/atomic_test.go index 7261159..8d03180 100644 --- a/sync2/atomic_test.go +++ b/sync2/atomic_test.go @@ -29,4 +29,21 @@ func TestAtomicString(t *testing.T) { if s.Get() != "c" { t.Errorf("want c, got %s", s.Get()) } + + var b AtomicBool + if b.Get() != false { + t.Fatal("must false") + } + + b.Set(true) + + if b.Get() != true { + t.Fatal("must true") + } + + b.Set(false) + + if b.Get() != false { + t.Fatal("must false") + } }