Add Bool.CAS for compare-and-swap semantics (#23)

This commit is contained in:
Prashant Varanasi
2017-05-09 12:57:10 -07:00
committed by GitHub
parent 1d7f075bbe
commit 3f020e6d5d
3 changed files with 14 additions and 0 deletions

View File

@@ -232,6 +232,11 @@ func (b *Bool) Load() bool {
return truthy(atomic.LoadUint32(&b.v))
}
// CAS is an atomic compare-and-swap.
func (b *Bool) CAS(old, new bool) bool {
return atomic.CompareAndSwapUint32(&b.v, boolToInt(old), boolToInt(new))
}
// Store atomically stores the passed value.
func (b *Bool) Store(new bool) {
atomic.StoreUint32(&b.v, boolToInt(new))

View File

@@ -108,6 +108,13 @@ func TestBool(t *testing.T) {
require.False(t, atom.Toggle(), "Expected swap to return previous value.")
require.True(t, atom.Load(), "Unexpected state after swap.")
require.True(t, atom.CAS(true, true), "CAS should swap when old matches")
require.True(t, atom.Load(), "CAS should have no effect")
require.True(t, atom.CAS(true, false), "CAS should swap when old matches")
require.False(t, atom.Load(), "CAS should have modified the value")
require.False(t, atom.CAS(true, false), "CAS should fail on old mismatch")
require.False(t, atom.Load(), "CAS should not have modified the value")
atom.Store(false)
require.False(t, atom.Load(), "Unexpected state after store.")

View File

@@ -122,6 +122,8 @@ func TestStressBool(t *testing.T) {
atom.Load()
atom.Store(false)
atom.Swap(true)
atom.CAS(true, false)
atom.CAS(true, false)
atom.Load()
atom.Toggle()
atom.Toggle()