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


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

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

用法:

func StoreUint32(addr *uint32, val uint32)

在此,addr表示地址。

注意:(* uint32)是指向uint32值的指針。但是,int32包含從0到4294967295的所有無符號32位整數的集合。

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



範例1:

// Program to illustrate the usage of 
// StoreUint32 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 uint32 
        y uint32 
    ) 
  
    // Using StoreUint32 method 
    // with its parameters 
    atomic.StoreUint32(&x, 465559) 
    atomic.StoreUint32(&y, 123) 
  
    // Displays the value stored in addr 
    fmt.Println(atomic.LoadUint32(&x)) 
    fmt.Println(atomic.LoadUint32(&y)) 
}

輸出:

465559
123

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

範例2:

// Program to illustrate the usage of 
// StoreUint32 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 uint32 
    ) 
  
    // Using StoreUint32 method  
    // with its parameters 
    atomic.StoreUint32(&x, 67677) 
  
    // Loading the stored val 
    z:= atomic.LoadUint32(&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.StoreUint32() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。