当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Golang atomic.StoreInt64()用法及代码示例


在Go语言中,原子包提供lower-level原子内存,这对实现同步算法很有帮助。 Go语言中的StoreInt64()函数用于将val原子存储到* addr中。此函数在原子包下定义。在这里,您需要导入“sync/atomic”软件包才能使用这些函数。

用法:

func StoreInt64(addr *int64, val int64)

在此,addr表示地址。

注意:(* int64)是指向int64值的指针。但是,int64包含从-9223372036854775808到9223372036854775807的所有带符号的64位整数的集合。

返回值:它将val存储到* addr中,然后在需要时可以返回。



范例1:

// Program to illustrate the usage of 
// StoreInt64 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 int64 
        y int64 
    ) 
  
    // Using StoreInt64 method  
    // with its parameters 
    atomic.StoreInt64(&x, 6777676777) 
    atomic.StoreInt64(&y, 98877) 
  
    // Displays the value stored in addr 
    fmt.Println(atomic.LoadInt64(&x)) 
    fmt.Println(atomic.LoadInt64(&y)) 
}

输出:

6777676777
98877

在这里,首先,将int64值存储在定义的地址中,然后使用上面的LoadInt64()方法将它们返回。

范例2:

// Program to illustrate the usage of 
// StoreInt64 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 int64 
    ) 
  
    // Using StoreInt64 method 
    // with its parameters 
    atomic.StoreInt64(&x, 3654567899788) 
  
    // Loading the stored val 
    z:= atomic.LoadInt64(&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.StoreInt64() Function in Golang With Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。