[轉]Golang atomic.CompareAndSwapInt64()實例講解

 

原文: http://www.manongjc.com/detail/30-anadyrrwgsoebxp.html

--------------

 

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

用法:

func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)

在這裏,addr表示地址,old表示int64值,它是從交換操作返回的舊交換值,而new則是int64新值,它將與舊交換值進行交換。

注意:(* int64)是指向int64值的指針。並且int64是位大小64的整數類型。此外,int64包含從-9223372036854775808到9223372036854775807的所有帶符號的64位整數的集合。

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



以下示例說明了上述方法的用法:

範例1:

// Golang Program to illustrate the usage of 
// CompareAndSwapInt64 function 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Assigning variable values to the int64 
    var ( 
        i int64 = 686788787 
    ) 
  
    // Swapping 
    var old_value = atomic.SwapInt64(&i, 56677) 
  
    // Printing old value and swapped value 
    fmt.Println("Swapped:", i, ", old value:", old_value) 
  
    // Calling CompareAndSwapInt64  
    // method with its parameters 
    Swap:= atomic.CompareAndSwapInt64(&i, 56677, 908998) 
  
    // Displays true if swapped else false 
    fmt.Println(Swap) 
    fmt.Println("The Value of i is:",i) 
}
 

輸出:

Swapped:56677 , old value:686788787
true
The Value of i is: 908998

範例2:

// Golang Program to illustrate the usage of 
// CompareAndSwapInt64 function 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Assigning variable values to the int64 
    var ( 
        i int64 = 686788787 
    ) 
  
    // Swapping 
    var old_value = atomic.SwapInt64(&i, 56677) 
  
    // Printing old value and swapped value 
    fmt.Println("Swapped:", i, ", old value:", old_value) 
  
    // Calling CompareAndSwapInt64  
    // method with its parameters 
    Swap:= atomic.CompareAndSwapInt64(&i, 686788787, 908998) 
  
    // Displays true if swapped else false 
    fmt.Println(Swap) 
    fmt.Println(i) 
}
 

輸出:

Swapped:56677, old value:686788787
false
56677

在這裏,CompareAndSwapInt64方法中的舊值必須是SwapInt64方法返回的交換值。此處不執行交換,因此返回false。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章