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


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

在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的CompareAndSwapUint64()函數用於對uint64值執行比較和交換操作。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。

用法:

func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)

在這裏,addr表示地址,old表示uint64值,它是舊的,而new表示uint64新值,它將與舊值交換自身。

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

返回值:如果交換完成,則返回true,否則返回false。



範例1:

// Golang Program to illustrate the usage of 
// CompareAndSwapUint64 function 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Assigning variable values to the uint64 
    var ( 
        i uint64 = 34764576575 
    ) 
  
    // Calling CompareAndSwapUint64 method with its parameters 
    Swap:= atomic.CompareAndSwapUint64(&i, 34764576575, 575765878) 
  
    // Displays true if swapped else false 
    fmt.Println(Swap) 
    fmt.Println("The new value of i is:",i) 
}

輸出:

true
The new value of i is: 575765878

範例2:

// Golang Program to illustrate the usage of 
// CompareAndSwapUint64 function 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Assigning variable  
    // values to the uint64 
    var ( 
        i uint64 = 143255757 
    ) 
  
    // Swapping operation. Here value of i become 
    // 4676778904 
    var oldvalue = atomic.SwapUint64(&i, 4676778904) 
  
    // Printing old value and swapped value 
    fmt.Println("Swapped_value:", i, ", old_value:", oldvalue) 
  
    // Calling CompareAndSwapUint64  
    // method with its parameters 
    Swap:= atomic.CompareAndSwapUint64(&i, 143255757, 9867757) 
  
    // Displays true if swapped else false 
    fmt.Println(Swap) 
    fmt.Println("The value of i is:",i) 
}

輸出:

Swapped_value:4676778904 , old_value:143255757
false
The value of i is: 4676778904

在此,從交換操作獲得的交換值必須是舊值。即4676778904,這就是返回false的原因。




相關用法


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