當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang atomic.StoreInt32()用法及代碼示例

在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的StoreInt32()函數用於將val原子存儲到* addr中。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。

用法:

func StoreInt32(addr *int32, val int32)

在此,addr表示地址。

注意:(* int32)是指向int32值的指針。但是,int32包含從-2147483648到2147483647的所有帶符號的32位整數的集合。

返回值:它將val存儲到* addr中,然後在需要時可以返回。



範例1:

// Program to illustrate the usage of 
// StoreInt32 function in Golang 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Defining variables for  
    // the address to store the val 
    var ( 
        x int32 
        y int32 
    ) 
  
    // Using StoreInt32 method  
    // with its parameters 
    atomic.StoreInt32(&x, 65) 
    atomic.StoreInt32(&y, 3455) 
  
    // Displays the value stored in addr 
    fmt.Println(atomic.LoadInt32(&x)) 
    fmt.Println(atomic.LoadInt32(&y)) 
}

輸出:

65
3455

在這裏,首先,將int32值存儲在定義的地址中,然後使用上述LoadInt32()方法將其返回。

範例2:

// Program to illustrate the usage of 
// StoreInt32 function in Golang 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Defining variables for  
    // the address to store the val 
    var ( 
        x int32 
    ) 
  
    // Using StoreInt32 method  
    // with its parameters 
    atomic.StoreInt32(&x, 8943) 
  
    // Loading the stored val 
    z:= atomic.LoadInt32(&x) 
  
    // Prints true if values  
    // are same else false 
    fmt.Println(z == x) 
  
    // Prints true if addresses 
    // are same else false 
    fmt.Println(&z == &x) 
}

輸出:

true
false

此處,存儲和加載的值相同,因此返回true,但其地址不同,因此在這種情況下返回false。




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 atomic.StoreInt32() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。