atomicx

package
v0.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2024 License: Apache-2.0 Imports: 1 Imported by: 32 modules, 31 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Value

type Value[T any] struct {
	// contains filtered or unexported fields
}

Value 是对 atomic.Value 的泛型封装 相比直接使用 atomic.Value, - Load 方法大概开销多了 0.5 ns - Store 方法多了不到 2 ns - Swap 方法多了 14 ns - CompareAndSwap 在失败的情况下,会多 2 ns,成功的时候多了 0.3 ns 使用 NewValue 或者 NewValueOf 来创建实例

func NewValue

func NewValue[T any]() *Value[T]

NewValue 会创建一个 Value 对象,里面存放着 T 的零值 注意,这个零值是带了类型的零值

Example
val := NewValue[int]()
data := val.Load()
fmt.Println(data)
Output:
0

func NewValueOf

func NewValueOf[T any](t T) *Value[T]

NewValueOf 会使用传入的值来创建一个 Value 对象

Example
val := NewValueOf[int](123)
data := val.Load()
fmt.Println(data)
Output:
123

func (*Value[T]) CompareAndSwap

func (v *Value[T]) CompareAndSwap(old, new T) (swapped bool)
Example
val := NewValueOf[int](123)
swapped := val.CompareAndSwap(123, 456)
fmt.Println(swapped)

swapped = val.CompareAndSwap(455, 459)
fmt.Println(swapped)
Output:
true
false

func (*Value[T]) Load

func (v *Value[T]) Load() (val T)
Example
val := NewValueOf[int](123)
data := val.Load()
fmt.Println(data)
Output:
123

func (*Value[T]) Store

func (v *Value[T]) Store(val T)
Example
val := NewValueOf[int](123)
data := val.Load()
fmt.Println(data)
val.Store(456)
data = val.Load()
fmt.Println(data)
Output:
123
456

func (*Value[T]) Swap

func (v *Value[T]) Swap(new T) (old T)
Example
val := NewValueOf[int](123)
oldVal := val.Swap(456)
newVal := val.Load()
fmt.Printf("old: %d, new: %d", oldVal, newVal)
Output:
old: 123, new: 456

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL