在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的CompareAndSwapPointer()函數用於對unsafe.Pointer值執行比較和交換操作。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。
用法:
func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool)
在這裏,addr表示地址,old表示不安全。Pointer值是從SwapPointer操作返回的舊交換值,而new是unsafe.Pointer的新值,它將與舊交換值交換自身。
注意:(* unsafe.Pointer)是指向unsafe.Pointer值的指針。而且unsafe.Pointer類型有助於啟用任意類型和內置uintptr類型之間的轉換。此外,不安全是有助於Go程序的類型安全的軟件包。
返回值:如果交換完成,則返回true,否則返回false。
範例1:
// Program to illustrate the usage of
// CompareAndSwapPointer function in Golang
// Including main package
package main
// Importing fmt,
// sync/atomic and unsafe
import (
"fmt"
"sync/atomic"
"unsafe"
)
// Defining a struct type P
type P struct{ x, y, z int }
// Declaring pointer
// to P struct type
var pP *P
// Main function
func main() {
// Defining addr unsafe.Pointer
var unsafe1 = (*unsafe.Pointer)(unsafe.Pointer(&pP))
// Old unsafe pointer
var sy P
// Defining new unasfe.pointer
px:= atomic.SwapPointer(
unsafe1, unsafe.Pointer(&sy))
// Calling CompareAndSwapPointer
// method with its parameters
y:= atomic.CompareAndSwapPointer(
unsafe1, unsafe.Pointer(&sy), px)
// Returns true if
// swapped else false
fmt.Println(y)
}
輸出:
true
範例2:
// Program to illustrate the usage of
// CompareAndSwapPointer function in Golang
// Including main package
package main
// importing fmt,
// sync/atomic and unsafe
import (
"fmt"
"sync/atomic"
"unsafe"
)
// Defining a struct type P
type P struct{ x, y, z int }
// Declaring pointer to P struct type
var pP *P
// Main function
func main() {
// Defining addr unsafe.Pointer
var unsafe1 = (*unsafe.Pointer)(unsafe.Pointer(&pP))
// Old unsafe pointer
var sy P
// Defining new unasfe.pointer
px:= atomic.SwapPointer(
unsafe1, unsafe.Pointer(&sy))
// Calling CompareAndSwapPointer
// method with its parameters
y:= atomic.CompareAndSwapPointer(
unsafe1, px, unsafe.Pointer(&sy))
// Returns true if
// swapped else false
fmt.Println(y)
}
輸出:
false
在上麵的示例中,不執行交換操作,因為CompareAndSwapPointer()方法中的舊值必須是SwapPointer()方法返回的值,但此處的舊值不同,因此上述代碼返回了false。
相關用法
- 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.CompareAndSwapPointer() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。