From 1b68eff1b3d892480a1976dc51714e30aa60450b Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Mon, 4 Nov 2019 16:52:07 +1100 Subject: Use atomic.Value for Var state --- var.go | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) (limited to 'var.go') diff --git a/var.go b/var.go index 51160e2..4859643 100644 --- a/var.go +++ b/var.go @@ -3,27 +3,22 @@ package stm import ( "sync" "sync/atomic" - "unsafe" ) // Holds an STM variable. type Var struct { - state *varSnapshot + state atomic.Value watchers sync.Map mu sync.Mutex } -func (v *Var) addr() *unsafe.Pointer { - return (*unsafe.Pointer)(unsafe.Pointer(&v.state)) -} - -func (v *Var) loadState() *varSnapshot { - return (*varSnapshot)(atomic.LoadPointer(v.addr())) +func (v *Var) loadState() varSnapshot { + return v.state.Load().(varSnapshot) } func (v *Var) changeValue(new interface{}) { version := v.loadState().version - atomic.StorePointer(v.addr(), unsafe.Pointer(&varSnapshot{version: version + 1, val: new})) + v.state.Store(varSnapshot{version: version + 1, val: new}) } type varSnapshot struct { @@ -33,9 +28,7 @@ type varSnapshot struct { // Returns a new STM variable. func NewVar(val interface{}) *Var { - return &Var{ - state: &varSnapshot{ - val: val, - }, - } + v := &Var{} + v.state.Store(varSnapshot{version: 0, val: val}) + return v } -- cgit v1.2.3