atomic.SwapInt32() Function in Golang With Examples

In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The SwapInt32() 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 SwapInt32(addr *int32, new int32) (old int32)

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



Note: (*int32) is the pointer to a int32 value. However, int32 contains the set of all signed 32-bit integers from -2147483648 to 2147483647.

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

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Stored new value:  6365654, Old value:  5435435

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

true
false

Here, the oldVal1 is equal to “m” as the new value to be stored in the *addr is same as the 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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.