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


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

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

用法:

func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)

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

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

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



範例1:

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

輸出:

Swapped:498 , old value:111
true
The Value of i is: 675

範例2:

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

輸出:

Swapped:498 , old value:111
false
The Value of i is: 498

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




相關用法


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