在 Go 语言中,原子包提供较低级别的原子内存,这有助于实现同步算法。 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!
在这里,值unsafe.Pointer存储在 *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 // Can be different at different run times
这里存储了声明的unsafe.Pointer val,并在此处返回存储的val的地址。此外,地址在不同的运行时间可以不同。