Golang atomic.StoreInt32() 函数及示例
在并发编程中,我们需要使用原子操作来实现对共享变量的安全操作。Golang 提供了 atomic 包,其中包含一些函数,可用于原子操作。其中 atomic.StoreInt32() 函数就是用于将一个 int32 类型的值在原子操作中存储到一个变量中。
atomic.StoreInt32() 函数的说明
atomic.StoreInt32() 函数的原型如下:
func StoreInt32(addr *int32, val int32)
其中,参数 addr
是一个指向 int32 类型变量的指针,表示要存储的变量地址,参数 val
是所要存储的 int32 类型的值。
函数的作用就是将参数 val
的值在原子操作中存储到 addr
指向的变量中。
atomic.StoreInt32() 函数的示例代码
为了更好地理解 atomic.StoreInt32() 函数的作用,我们来看一个使用示例。
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var num int32
fmt.Println("num before store:", num)
atomic.StoreInt32(&num, 10)
fmt.Println("num after store:", num)
}
上面的代码中,我们定义了一个变量 num
,并初始化为 0。然后我们使用 atomic.StoreInt32() 函数将值 10 存储到 num
变量中。
在存储之前我们打印了变量 num
的值,在存储之后再次打印,观察其变化。
运行上面的代码,输出如下:
num before store: 0
num after store: 10
我们可以看到,在使用 atomic.StoreInt32() 函数后,变量 num
的值被成功地更改为 10。
结论
atomic.StoreInt32() 函数可用于将 int32 类型的值在原子操作中存储到一个变量中。在并发编程中,使用原子操作可以避免线程安全问题的发生。