在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的LoadInt32()函數用於原子加載* addr。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。
用法:
func LoadInt32(addr *int32) (val int32)
在此,addr表示地址。
注意:(* int32)是指向int32值的指針。但是,int32包含從-2147483648到2147483647的所有帶符號的32位整數的集合。
返回值:它返回加載到地址的值。
範例1:
// Program to illustrate the usage of
// LoadInt32 function in Golang
// Including main package
package main
// importing fmt and sync/atomic
import (
"fmt"
"sync/atomic"
)
// Main function
func main() {
// Assigning values to the int32
var (
i int32 = 57567
j int32 = -842
k int32 = 17
l int32 = 3455
)
// Calling LoadInt32 method
// with its parameters
load_1:= atomic.LoadInt32(&i)
load_2:= atomic.LoadInt32(&j)
load_3:= atomic.LoadInt32(&k)
load_4:= atomic.LoadInt32(&l)
// Displays the int32 value
// loaded in the *addr
fmt.Println(load_1)
fmt.Println(load_2)
fmt.Println(load_3)
fmt.Println(load_4)
}
輸出:
57567 -842 17 3455
範例2:
// Program to illustrate the usage of
// LoadInt32 function in Golang
// Including main package
package main
// Importing fmt and sync/atomic
import (
"fmt"
"sync/atomic"
)
// Main function
func main() {
// Declaring x
var x int32
// For loop
for i:= 1; i < 789; i += 2 {
// Function with AddInt32 method
go func() {
atomic.AddInt32(&x, 4)
}()
}
// Prints loaded values address
fmt.Println(atomic.LoadInt32(&x))
}
輸出:
1416 // A random value is returned in each run
在上麵的示例中,每次調用都會從AddInt32()方法返回新值,直到循環停止為止,LoadInt32()方法將加載這些新的int32值。而且這些值存儲在不同的地址中,該地址可以是隨機的,因此,每次運行中LoadInt32()方法的輸出都是不同的。因此,這裏在輸出中返回一個隨機值。
相關用法
- 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.LoadInt32() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。