在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Golang中的AddInt32()函數用於將增量自動添加到* addr。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。
用法:
func AddInt32(addr *int32, delta int32) (new int32)
在此,addr表示地址,而delta表示少量大於零的位。
注意:(* int32)是指向int32值的指針。此外,int32包含從-2147483648到2147483647的所有帶符號的32位整數的集合。
返回值:它自動添加addr和delta並返回一個新值。
範例1:
// Golang Program to illustrate the usage of
// AddInt32 function
// 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 = 97
j int32 = 48
k int32 = 34754567
l int32 = -355363
)
// Assigning constant
// values to int32
const (
x int32 = 4
y int32 = 2
)
// Calling AddInt32 method
// with its parameters
res_1:= atomic.AddInt32(&i, y)
res_2:= atomic.AddInt32(&j, y-1)
res_3:= atomic.AddInt32(&k, x-1)
res_4:= atomic.AddInt32(&l, x)
// Displays the output after adding
// addr and delta automically
fmt.Println(res_1)
fmt.Println(res_2)
fmt.Println(res_3)
fmt.Println(res_4)
}
輸出:
99 49 34754570 -355359
範例2:
// Golang Program to illustrate the usage of
// AddInt32 function
// Including main package
package main
// importing fmt and sync/atomic
import (
"fmt"
"sync/atomic"
)
// Defining addr of type int32
type addr int32
// function that adds addr and delta
func (x *addr) add() int32 {
// Calling AddInt32() function
// with its parameter
return atomic.AddInt32((*int32)(x), 2)
}
// Main function
func main() {
// Defining x
var x addr
// For loop to increment
// the value of x
for i:= 1; i < 7; i++ {
// Displays the new value
// after adding delta and addr
fmt.Println(x.add())
}
}
輸出:
2 4 6 8 10 12
在上麵的示例中,我們定義了一個函數add,該函數返回調用AddInt32方法返回的輸出。在主函數中,我們定義了一個“for”循環,該循環將在每個調用中增加‘x’的值。在這裏,AddInt32()方法的第二個參數是恒定的,隻有第一個參數的值是可變的。但是,上一個調用的輸出將是下一個調用中AddInt32()方法的第一個參數的值,直到循環停止為止。
讓我們看看上麵的示例如何工作:
1st parameter = 0, 2nd parameter = 2 // returns ( 0 + 2 = 2) // Now, the above output is 1st parameter in next call to AddInt32() method 1st parameter = 2, 2nd parameter = 2 // returns ( 2 + 2 = 4) 1st parameter = 4, 2nd parameter = 2 // returns ( 4 + 2 = 6) and so on.
相關用法
- 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.AddInt32() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。