在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的SwapUintptr()函數用於將新值自動存儲到* addr中,並返回先前的* addr值。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。
用法:
func SwapUintptr(addr *uintptr, new uintptr) (old uintptr)
在此,addr表示地址。而new是新的uintptr值,而old是舊的uintptr值。
注意:(* uintptr)是指向uintptr值的指針。 uintptr是一個太大的整數類型,它不能包含任何指針的位模式。
返回值:它將新的uintptr值存儲到* addr中,並返回先前的* addr值。
範例1:
// Program to illustrate the usage of
// SwapUintptr function in Golang
// Including main package
package main
// Importing fmt and sync/atomic
import (
"fmt"
"sync/atomic"
)
// Main function
func main() {
// Assigning value to uintptr
var x uintptr = 96464646466757
// Using SwapUintptr method
// with its parameters
var old_val = atomic.SwapUintptr(&x,
21863567864)
// Prints new and old value
fmt.Println("Stored new value:",
x, ", Old value:", old_val)
}
輸出:
Stored new value: 21863567864, Old value: 96464646466757
範例2:
// Program to illustrate the usage of
// SwapUintptr function in Golang
// Including main package
package main
// Importing fmt and sync/atomic
import (
"fmt"
"sync/atomic"
)
// Main function
func main() {
// Assigning value to uintptr
var m uintptr = 4235564747474
var n uintptr = 2567891937466
// Using SwapUintptr method with its parameters
var oldVal1 = atomic.SwapUintptr(&m, 4235564747474)
var oldVal2 = atomic.SwapUintptr(&n, 7454545419024)
// Prints output
fmt.Println((oldVal1) == m)
fmt.Println((oldVal2) == n)
}
輸出:
true false
這裏,oldVal1等於“m”,因為要存儲在* addr中的新值與舊值相同,因此,返回true,但oldVal2不等於“n”,因為那裏的舊值與新分配的值不相似,因此,則返回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.SwapUintptr() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。