在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的SwapPointer()函數用於將新值自動存儲到* addr中,並返回先前的* addr值。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。
用法:
func SwapPointer(addr *unsafe.Pointer, new unsafe.Pointer) (old unsafe.Pointer)
在此,addr表示地址。而new是新的unsafe.Pointer值,而old是舊的unsafe.Pointer值。
注意:(* unsafe.Pointer)是指向unsafe.Pointer值的指針。而且unsafe.Pointer類型有助於啟用任意類型和內置uintptr類型之間的轉換。此外,不安全是有助於Go程序的類型安全的軟件包。
返回值:它將新的unsafe.Pointer值存儲到* addr中,並返回先前的* addr值。
範例1:
// Program to illustrate the usage of
// SwapPointer function in Golang
// Including main package
package main
// Importing fmt and sync/atomic
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
// Main function
func main() {
// Defining *addr unsafe.Pointer
var unsafepL = (*unsafe.Pointer)(unsafe.Pointer(&PL))
// Defining values
// of unsafe.Pointer
var px, py L
// Storing value to the pointer
atomic.StorePointer(
unsafepL, unsafe.Pointer(&px))
// Calling SwapPointer() method
px1:= atomic.SwapPointer(unsafepL,
unsafe.Pointer(&py))
// Returns true if swapped
fmt.Println((*L)(px1) == &px)
// Prints output
fmt.Println(px1)
}
輸出:
true 0xc0000c2000 // Can be different at different run times
在這裏,StorePointer方法將值添加到* addr,然後SwapPointer方法將新值自動存儲到* addr中並返回舊值。並且,在此完成交換,因此返回true,並且不安全的值。此處返回的Pointer在不同的運行時間可能會有所不同。
範例2:
// Program to illustrate the usage of
// SwapPointer function in Golang
// Including main package
package main
// Importing fmt and sync/atomic
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
// Main function
func main() {
// Defining *addr unsafe.Pointer
var unsafepL = (*unsafe.Pointer)(unsafe.Pointer(&PL))
// Defining values of unsafe.Pointer
var px, py L
// Calling SwapPointer() method
px1:= atomic.SwapPointer(unsafepL,
unsafe.Pointer(&py))
// Returns true if swapped
fmt.Println((*L)(px1) == &px)
// Prints output
fmt.Println(&px1)
}
輸出:
false 0xc00000e028 // Can be different at different run times
此處,返回false,因為在此之前不存儲unsafe.pointer,因此SwapPointer()方法無法交換指定的值。此外,此處返回的地址值是px1的地址,而px1的值將為零,因為未執行交換。
相關用法
- 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.SwapPointer() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。