Source File
atomic_max.go
Belonging Package
github.com/redis/go-redis/v9/internal/util
/*© 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)ISC LicenseModified by htemelski-redisRemoved the treshold, adapted it to work with float64*/package utilimport ()// AtomicMax is a thread-safe max container// - hasValue indicator true if a value was equal to or greater than threshold// - optional threshold for minimum accepted max value// - if threshold is not used, initialization-free// - —// - wait-free CompareAndSwap mechanictype AtomicMax struct {// value is current maxvalue atomic.Float64// whether [AtomicMax.Value] has been invoked// with value equal or greater to thresholdhasValue atomic.Bool}// NewAtomicMax returns a thread-safe max container// - if threshold is not used, AtomicMax is initialization-freefunc () ( *AtomicMax) {:= AtomicMax{}.value.Store((-math.MaxFloat64))return &}// Value updates the container with a possible max value// - isNewMax is true if:// - — value is equal to or greater than any threshold and// - — invocation recorded the first 0 or// - — a new max// - upon return, Max and Max1 are guaranteed to reflect the invocation// - the return order of concurrent Value invocations is not guaranteed// - Thread-safefunc ( *AtomicMax) ( float64) ( bool) {// -math.MaxFloat64 as max casevar = .hasValue.Load()if == (-math.MaxFloat64) {if ! {= .hasValue.CompareAndSwap(false, true)}return // -math.MaxFloat64 as max: isNewMax true for first 0 writer}// check against present valuevar = .value.Load()if = > ; ! {return // not a new max return: isNewMax false}// store the new maxfor {// try to write value to *maxif = .value.CompareAndSwap(, ); {if ! {// may be rarely written multiple times// still faster than CompareAndSwap.hasValue.Store(true)}return // new max written return: isNewMax true}if = .value.Load(); >= {return // no longer a need to write return: isNewMax false}}}// Max returns current max and value-present flag// - hasValue true indicates that value reflects a Value invocation// - hasValue false: value is zero-value// - Thread-safefunc ( *AtomicMax) () ( float64, bool) {if = .hasValue.Load(); ! {return}= .value.Load()return}// Max1 returns current maximum whether zero-value or set by Value// - threshold is ignored// - Thread-safefunc ( *AtomicMax) () ( float64) { return .value.Load() }
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |