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