Golang atomic.Load()函数及示例

Golang atomic.Load()函数及示例

Go 语言中,atomic 包提供了更低级别的原子内存,有助于实现同步算法。在 Go 语言中, Load() 函数用于检查最新值的值设置,如 Store 方法所存储的值,此外,如果未对该 Value 进行 Store 方法的任何调用,它还可以返回 nil。这个函数在 atomic 包中定义。在这里,您需要导入“sync/atomic”包,以便使用这些函数。

语法:

func (v *Value) Load() (x interface{})
Go

在这里,v 是任何类型的值,x 是 Load 和 Store 方法的输出结果类型。

注意:(*Value)是指向 Value 类型的指针。标准库中提供的 Value 类型是用于原子地加载和存储任何类型的值。

返回值:它返回 Store 方法存储的设置值。并且如果没有调用 store 方法,也可以返回 nil。

示例 1:

// Program to illustrate the usage of
// Load function in Golang
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Defining a struct type L
    type L struct{ x, y, z int }
  
    // Defining a variable to assign
    // values to the struct type L
    var r1 = L{9, 10, 11}
  
    // Defining Value type to store
    // values of any type
    var V atomic.Value
  
    // Calling Store function
    V.Store(r1)
  
    // Calling Load method
    var r2 = V.Load().(L)
  
    // Prints values as
    // stored by recent
    // store method
    fmt.Println(r2)
  
    // Displays true if satisfied
    fmt.Println(r1 == r2)
} 
Go

输出:

{9 10 11}
true
Go

在上面的示例中,我们使用 Value 类型来存储任何类型的值。这些值存储在被声明的接口 r1 上。但是,这些值可以使用 Load 方法返回。

示例 2:

// Program to illustrate the usage of
// Load function in Golang
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Defining a struct type L
    type L struct{ x, y, z int }
  
    // Defining a variable to assign
    // values to the struct type L
    var r1 = L{9, 10, 11}
  
    // Defining Value type to store
    // values of any type
    var V atomic.Value
  
    // Calling Load method
    var r2 = V.Load().(L)
  
    // Prints values as 
    // stored by recent
    // store method
    fmt.Println(r2)
  
    // Displays true if satisfied
    fmt.Println(r1 == r2)
} 
Go

输出:

panic: interface conversion: interface {} is nil, not main.L

goroutine 1 [running]:
main.main()
    /tmp/sandbox731326366/prog.go:28 +0x240
Go

在这里,未进行存储方法调用,因此返回 nil。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册