-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcell.go
More file actions
42 lines (35 loc) · 811 Bytes
/
cell.go
File metadata and controls
42 lines (35 loc) · 811 Bytes
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
package mrpkg
import (
"github.com/Boyux/mrpkg/option"
"golang.org/x/exp/constraints"
"sync/atomic"
)
type Cell[T any] struct {
inner atomic.Value
}
func (cell *Cell[T]) Store(value T) {
cell.inner.Store(value)
}
func (cell *Cell[T]) Load() (value option.Option[T]) {
if v := cell.inner.Load(); v != nil {
return option.Some(v.(T))
}
return option.None[T]()
}
func (cell *Cell[T]) CompareAndSwap(old, new T) (swapped bool) {
return cell.inner.CompareAndSwap(old, new)
}
func AtomicAdd[T constraints.Integer](cell *Cell[T], value T) T {
if v := cell.Load(); option.IsNull(v) {
if cell.inner.CompareAndSwap(nil, value) {
return value
}
}
for {
oldValue := cell.Load().Unwrap()
newValue := oldValue + value
if cell.CompareAndSwap(oldValue, newValue) {
return newValue
}
}
}