在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的SwapUint64()函數用於將新值原子存儲到* addr中,並返回先前的* addr值。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。
用法:
func SwapUint64(addr *uint64, new uint64) (old uint64)
在此,addr表示地址。而new是新的uint64值,而old是舊的uint64值。
注意:(* uint64)是指向uint64值的指針。 uint64是位大小為64的整數類型。但是,uint64包含從0到18446744073709551615的所有無符號64位整數的集合。
返回值:它將新的uint64值存儲到* addr中,並返回先前的* addr值。
範例1:
// Program to illustrate the usage of
// SwapUint64 function in Golang
// Including main package
package main
// Importing fmt and sync/atomic
import (
"fmt"
"sync/atomic"
)
// Main function
func main() {
// Assigning value to uint64
var x uint64 = 10864545453
// Using SwapUint64 method
// with its parameters
var old_val = atomic.SwapUint64(&x, 65353443)
// Prints new and old value
fmt.Println("Stored new value:",
x, ", Old value:", old_val)
}
輸出:
Stored new value: 65353443, Old value: 10864545453
範例2:
// Program to illustrate the usage of
// SwapUint64 function in Golang
// Including main package
package main
// Importing fmt and sync/atomic
import (
"fmt"
"sync/atomic"
)
// Main function
func main() {
// Assigning value to uint64
var m uint64 = 11735344343
var n uint64 = 976364747
// Using SwapUint64 method
// with its parameters
var oldVal1 = atomic.SwapUint64(&m, 11735344343)
var oldVal2 = atomic.SwapUint64(&n, 6586850111)
// 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.SwapUint64() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。