-
Notifications
You must be signed in to change notification settings - Fork 1
/
atomic-max.go
60 lines (49 loc) · 1.29 KB
/
atomic-max.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
© 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
ISC License
*/
package parl
import (
"sync/atomic"
"github.com/haraldrudell/parl/ints"
"golang.org/x/exp/constraints"
)
type AtomicMax[T constraints.Integer] struct {
value atomic.Uint64
hasValue atomic.Bool
}
func NewAtomicMax[T constraints.Integer](value T) (atomicMax *AtomicMax[T]) {
m := AtomicMax[T]{}
if value != 0 {
m.value.Store(uint64(value)) // set initial threshold
}
return &m
}
func (m *AtomicMax[T]) Value(value T) (isNewMax bool) {
// check if value is a new max
valueU64, err := ints.Unsigned[uint64](value, "")
if err != nil {
panic(err) // value out of range, ie. negative
}
var current = m.value.Load()
if isNewMax = valueU64 > current; !isNewMax {
return // not a new max return
}
m.hasValue.CompareAndSwap(false, true)
// store the new max
for {
// try to write value to *max
if m.value.CompareAndSwap(current, valueU64) {
return // new max written return
}
if current = m.value.Load(); current >= valueU64 {
return // no longer a need to write return
}
}
}
func (m *AtomicMax[T]) Max() (value T, hasValue bool) {
return T(m.value.Load()), m.hasValue.Load()
}
func (m *AtomicMax[T]) Max1() (value T) {
return T(m.value.Load())
}