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


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

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

用法:

func CompareAndSwapUintptr(addr *uintptr, old, new uintptr) (swapped bool)

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

注意:(* uintptr)是指向uintptr值的指針。 uintptr是一個無符號的整數類型,該類型太大,並且包含任何指針的位模式。

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



範例1:

// Program to illustrate the usage of 
// CompareAndSwapUintptr function in Golang 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Assigning variable 
    // values to the uintptr 
    var ( 
        i uintptr = 34764686 
        j uintptr = 41343432525245 
        k uintptr = 0 
    ) 
  
    // Calling CompareAndSwapUintptr  
    // method with its parameters 
    Swap1:= atomic.CompareAndSwapUintptr(&i, 
                         34764686, 647567565) 
      
    Swap2:= atomic.CompareAndSwapUintptr(&j, 
                          41343432525245, 76) 
      
    Swap3:= atomic.CompareAndSwapUintptr(&k, 
                                       0, 15) 
  
    // Displays true if  
    // swapped else false 
    fmt.Println(Swap1) 
    fmt.Println(Swap2) 
    fmt.Println(Swap3) 
  
    // Prints addr 
    fmt.Println(i) 
    fmt.Println(j) 
    fmt.Println(k) 
}

輸出:

true
true
true
647567565
76
15

範例2:

// Program to illustrate the usage of 
// CompareAndSwapUintptr function in Golang 
  
// Including main package 
package main 
  
// Importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  
// Main function 
func main() { 
  
    // Assigning variable  
    // values to the uintptr 
    var ( 
        x uintptr = 56466244 
    ) 
  
    // Swapping operation 
    var oldvalue = atomic.SwapUintptr(&x, 2344444) 
  
    // Printing old value  
    // and swapped value 
    fmt.Println("Swapped_value:", x, 
            ", old_value:", oldvalue) 
  
    // Calling CompareAndSwapUintptr  
    // method with its parameters 
    Swap:= atomic.CompareAndSwapUintptr(&x, 
                         56466244, 13232324) 
  
    // Displays true if  
    // swapped else false 
    fmt.Println(Swap) 
    fmt.Println(x) 
}

輸出:

Swapped_value:2344444, old_value:56466244
false
2344444

在此,從交換操作獲得的交換值必須是CompareAndSwapUintptr()方法的舊值,但此處的舊值是交換操作的舊值,這是不正確的,這就是返回false的原因。




相關用法


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