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


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

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

用法:

func StoreUint64(addr *uint64, val uint64)

在此,addr表示地址。

注意:(* uint64)是指向uint64值的指針。 uint64是位大小為64的整數類型。但是,int64包含從0到18446744073709551615的所有無符號64位整數的集合。

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



範例1:

// Program to illustrate the usage of 
// StoreUint64 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 uint64 
        y uint64 
    ) 
  
    // Using StoreUint64 method 
    // with its parameters 
    atomic.StoreUint64(&x, 56576656555555) 
    atomic.StoreUint64(&y, 0) 
  
    // Displays the value 
    // stored in addr 
    fmt.Println(atomic.LoadUint64(&x)) 
    fmt.Println(atomic.LoadUint64(&y)) 
}

輸出:

56576656555555
0

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

範例2:

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