在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的StorePointer()函數用於將val原子存儲到* addr中。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”包才能使用這些函數。
用法:
func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)
在此,addr表示地址。
注意:(* unsafe.Pointer)是指向unsafe.Pointer值的指針。而且unsafe.Pointer類型有助於啟用任意類型和內置uintptr類型之間的轉換。此外,不安全是有助於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的地址。此外,地址在不同的運行時間可以不同。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 atomic.StorePointer() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。