diff --git a/clientv3/ordering/kv.go b/clientv3/ordering/kv.go index 8e4d848133d5..e8bf07b8c741 100644 --- a/clientv3/ordering/kv.go +++ b/clientv3/ordering/kv.go @@ -17,7 +17,6 @@ package ordering import ( "context" "sync" - "sync/atomic" "github.com/coreos/etcd/clientv3" ) @@ -29,25 +28,25 @@ type kvOrdering struct { clientv3.KV orderViolationFunc OrderViolationFunc prevRev int64 + revMu sync.RWMutex } func NewKV(kv clientv3.KV, orderViolationFunc OrderViolationFunc) *kvOrdering { - return &kvOrdering{kv, orderViolationFunc, 0} + return &kvOrdering{kv, orderViolationFunc, 0, sync.RWMutex{}} } func (kv *kvOrdering) getPrevRev() int64 { - return atomic.LoadInt64(&kv.prevRev) + kv.revMu.RLock() + defer kv.revMu.RUnlock() + return kv.prevRev } func (kv *kvOrdering) setPrevRev(currRev int64) { - for { - prevRev := kv.getPrevRev() - if prevRev > currRev { - return - } - if atomic.CompareAndSwapInt64(&kv.prevRev, prevRev, currRev) { - return - } + prevRev := kv.getPrevRev() + kv.revMu.Lock() + defer kv.revMu.Unlock() + if currRev > prevRev { + kv.prevRev = currRev } } diff --git a/clientv3/ordering/kv_test.go b/clientv3/ordering/kv_test.go index b367d91fca81..b923cab3de46 100644 --- a/clientv3/ordering/kv_test.go +++ b/clientv3/ordering/kv_test.go @@ -214,6 +214,7 @@ func TestKvOrdering(t *testing.T) { } }(tt.response), tt.prevRev, + sync.RWMutex{}, } res, err := kv.Get(nil, "mockKey") if err != nil { @@ -267,6 +268,7 @@ func TestTxnOrdering(t *testing.T) { } }(tt.response), tt.prevRev, + sync.RWMutex{}, } txn := &txnOrdering{ kv.Txn(context.Background()),