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