From 377cfd813d4c36fed538274136b85f06fe364613 Mon Sep 17 00:00:00 2001 From: Jamie Liu Date: Tue, 22 Feb 2022 12:22:01 -0800 Subject: [PATCH] Add sync.SeqCount.BeginWriteOk. PiperOrigin-RevId: 430268914 --- pkg/sync/seqcount.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/pkg/sync/seqcount.go b/pkg/sync/seqcount.go index 1f025f33c..9bf4a1853 100644 --- a/pkg/sync/seqcount.go +++ b/pkg/sync/seqcount.go @@ -117,7 +117,17 @@ func (s *SeqCount) BeginWrite() { } } -// EndWrite ends the effect of a preceding BeginWrite. +// BeginWriteOk combines the semantics of ReadOk and BeginWrite. If the reader +// critical section initiated by a previous call to BeginRead() that returned +// epoch did not race with any writer critical sections, it begins a writer +// critical section and returns true. Otherwise it does nothing and returns +// false. +func (s *SeqCount) BeginWriteOk(epoch SeqCountEpoch) bool { + return atomic.CompareAndSwapUint32(&s.epoch, uint32(epoch), uint32(epoch)+1) +} + +// EndWrite ends the effect of a preceding BeginWrite or successful +// BeginWriteOk. func (s *SeqCount) EndWrite() { if epoch := atomic.AddUint32(&s.epoch, 1); epoch&1 != 0 { panic("SeqCount.EndWrite outside writer critical section")