Golang atomic.StoreInt32() 函数及示例
在 Go 语言中,原子包提供了较低级别的原子内存,有助于实现同步算法。Golang 中的 StoreInt32() 函数用于原子地将 val 存储到 *addr 中。该函数在 atomic 包中定义。您需要导入 “sync/atomic” 包才能使用这些函数。
语法:
func StoreInt32(addr *int32, val int32)
这里,addr 指示地址。
注意:(*int32) 是指向 int32 值的指针。但是,int32 包含所有带符号的 32 位整数的集合,范围从 -2147483648 到 2147483647。
返回值:它将 val 存储到 *addr 中,可以在需要时返回。
示例1:
// 用于说明
// Golang 中 StoreInt32 函数的使用
// 包含 main 函数
package main
// 导入 fmt 和 sync/atomic
import (
"fmt"
"sync/atomic"
)
// 主函数
func main() {
// 为存储 val 的地址定义变量
var (
x int32
y int32
)
// 使用带有其参数的 StoreInt32 方法
atomic.StoreInt32(&x, 65)
atomic.StoreInt32(&y, 3455)
// 显示存储在地址中的值
fmt.Println(atomic.LoadInt32(&x))
fmt.Println(atomic.LoadInt32(&y))
}
输出:
65
3455
这里,首先将 int32 值存储在定义的地址中,然后使用上方的 LoadInt32() 方法返回它们。
示例2:
// 用于说明
// Golang 中 StoreInt32 函数的使用
// 包含 main 函数
package main
// 导入 fmt 和 sync/atomic
import (
"fmt"
"sync/atomic"
)
// 主函数
func main() {
// 为存储 val 的地址定义变量
var (
x int32
)
// 使用带有其参数的 StoreInt32 方法
atomic.StoreInt32(&x, 8943)
// 加载存储的 val
z := atomic.LoadInt32(&x)
// 如果值相同,则返回 true,否则为 false
fmt.Println(z == x)
// 如果地址相同,则返回 true,否则为 false
fmt.Println(&z == &x)
}
输出:
true
false
这里,存储和加载的值相同,因此返回 true,但它们的地址不同,因此在这种情况下返回 false。
极客教程