Golang atomic.StorePointer()函数及其示例
在Go语言中,atomic库提供了较低级别的原子内存操作,有助于实现同步算法。Go语言中的 StorePointer() 函数用于将val以原子方式存储到*addr中。这个函数定义在atomic库中。你需要导入”sync/atomic”包以使用这些函数。
语法:
func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)
其中,addr表示地址。
注意:(*unsafe.Pointer)是一个指向unsafe.Pointer值的指针。unsafe.Pointer类型有助于在任意类型和内置uintptr类型之间进行转换。另外,unsafe是一个有助于Go程序类型安全的包。
返回值:它将val存储到*addr中,并可以在需要时返回。
示例1:
// Program to illustrate the usage of
// StorePointer function in Golang
// Including main package
package main
// importing fmt,
// sync/atomic and unsafe
import (
"fmt"
"sync/atomic"
"unsafe"
)
// Defining a struct type L
type L struct{ x, y, z int }
// Declaring pointer
// to L struct type
var PL *L
// Calling main
func main() {
// Defining *addr unsafe.Pointer
var unsafepL = (*unsafe.Pointer)(unsafe.Pointer(&PL))
// Defining value
// of unsafe.Pointer
var px L
// Calling StorePointer and
// storing unsafe.Pointer
// value to *addr
atomic.StorePointer(
unsafepL, unsafe.Pointer(&px))
// Printed if value is stored
fmt.Println("Val Stored!")
}
输出:
Val Stored!
在这里,将不安全指针存储在*addr中,因此上面的代码返回了指定的输出。
示例2:
// Program to illustrate the usage of
// StorePointer function in Golang
// Including main package
package main
// importing fmt,
// sync/atomic and unsafe
import (
"fmt"
"sync/atomic"
"unsafe"
)
// Defining a struct type L
type L struct{ x, y, z int }
// Declaring pointer to L struct type
var PL *L
// Calling main
func main() {
// Defining *addr unsafe.Pointer
var unsafepL = (*unsafe.Pointer)(unsafe.Pointer(&PL))
// Defining value
// of unsafe.Pointer
var px = 54634763
// Calling StorePointer and
// storing unsafe.Pointer
// value to *addr
atomic.StorePointer(
unsafepL, unsafe.Pointer(&px))
// Prints the value of the
// address where val is stored
fmt.Println(&px)
}
输出:
0xc0000b6010 // 在不同的运行时间可能会不同
在这里,所述的不安全的指针值已存储,并返回了存储值的地址。此外,存储地址可能在不同的运行时间发生变化。
极客教程