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


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

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

用法:

func StoreUintptr(addr *uintptr, val uintptr)

在此,addr表示地址。

注意:(* uintptr)是指向uintptr值的指針。 uintptr是一個太大的整數類型,它不能包含任何指針的位模式。

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



範例1:

// Program to illustrate the usage of 
// StoreUintptr 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 uintptr 
        y uintptr 
    ) 
  
    // Using StoreUintptr method 
    // with its parameters 
    atomic.StoreUintptr(&x, 444443) 
    atomic.StoreUintptr(&y, 223) 
  
    // Displays the value stored in addr 
    fmt.Println(atomic.LoadUintptr(&x)) 
    fmt.Println(atomic.LoadUintptr(&y)) 
}

輸出:

444443
223

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

範例2:

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