Skip to content
Related Articles

Related Articles

Improve Article
atomic.SwapUint32() Function in Golang With Examples
  • Last Updated : 01 Apr, 2020

In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The SwapUint32() function in Go language is used to atomically store new value into *addr and returns the previous *addr value. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.

Syntax:

func SwapUint32(addr *uint32, new uint32) (old uint32)

Here, addr indicates address. And new is the new uint32 value and old is the older uint32 value.

Note: (*uint32) is the pointer to a uint32 value. However, int32 contains the set of all unsigned 32-bit integers from 0 to 4294967295.

Return value: It stores the new uint32 value into the *addr and returns the previous *addr value.



Example 1:




// Program to illustrate the usage of
// SwapUint32 function in Golang
  
// Including main package
package main
  
// Importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Assigning value to uint32
    var x uint32 = 18384411
  
    // Using SwapUint32 method 
    // with its parameters
    var old_val = atomic.SwapUint32(&x, 324233535)
  
    // Prints new and old value
    fmt.Println("Stored new value: ",
         x, ", Old value: ", old_val)
}

Output:

Stored new value:  324233535, Old value:  18384411

Example 2:




// Program to illustrate the usage of
// SwapUint32 function in Golang
  
// Including main package
package main
  
// Importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Assigning value to uint32
    var m uint32 = 856677902
    var n uint32 = 123455608
  
    // Using SwapUint32 method with its parameters
    var oldVal1 = atomic.SwapUint32(&m, 856677902)
    var oldVal2 = atomic.SwapUint32(&n, 9676821)
  
    // Prints output
    fmt.Println((oldVal1) == m)
    fmt.Println((oldVal2) == n)
}

Output:

true
false

Here, the oldVal1 is equal to “m” as the new value to be stored in the *addr is same as an old value so, true is returned but oldVal2 is not equal to “n” as there the old value is not similar to the newly assigned value hence, false is returned.




My Personal Notes arrow_drop_up
Recommended Articles
Page :