Menu Close

Go – CompareAndSwapInt64 in atomic package

In this article, we will explore the CompareAndSwapInt64 Function in sync/atomic package in Go in details, along with examples.

CompareAndSwapInt64 function in atomic package performs an atomic compare-and-swap operation on a given signed 64-bit integer (int64). The function signature is as follows:

Syntax:

func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)
  • addr: A pointer to the int64 value you want to update atomically.
  • old: The expected current value of the int64 at addr.
  • new: The int64 value you want to replace the current value with if the comparison succeeds.

The function returns a boolean value indicating whether the swap was successful (true) or not (false).

Using CompareAndSwapInt64 in Go

In concurrent programming, multiple goroutines can access and modify shared data simultaneously, which can lead to race conditions and incorrect results. The CompareAndSwapInt64 function can be used to conditionally update shared data based on its current value, ensuring that the operation is performed atomically and preventing any data races or inconsistencies.

Here’s an example of how to use the CompareAndSwapInt64 function to safely update a shared int64 value from multiple goroutines:

Example

package main


import (

	"fmt"

	"math/rand"

	"sync"

	"sync/atomic"

	"time"

)


var sharedValue int64


func main() {

	rand.Seed(time.Now().UnixNano())

	var wg sync.WaitGroup

	wg.Add(10)


	for i := 0; i < 10; i++ {

		go func() {

			defer wg.Done()

			for j := 0; j < 5; j++ {

				time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)

				oldValue := atomic.LoadInt64(&sharedValue)

				newValue := oldValue + 1

				swapped := atomic.CompareAndSwapInt64(&sharedValue, oldValue, newValue)

				if swapped {

					fmt.Printf("Swapped: %d -> %d\n", oldValue, newValue)

				} else {

					fmt.Printf("Failed to swap: %d != %d\n", sharedValue, oldValue)

				}

			}

		}()

	}


	wg.Wait()

	fmt.Printf("Final shared value: %d\n", sharedValue)

}

In this example, we create a global sharedValue variable of type int64. Then, we launch 10 goroutines, each of which tries to increment the shared value 5 times using CompareAndSwapInt64. The sync.WaitGroup is used to ensure that the main goroutine waits for all the other goroutines to finish their execution.

After all goroutines have finished, the main goroutine prints the final value of the shared variable. Since we used CompareAndSwapInt64 to update the shared value atomically, we can be confident that the final value is correct and free of data races.

To check more Go related articles. Pls click given below link:

https://www.techieindoor.com/go-net-package-in-go-golang/

https://pkg.go.dev/net/[email protected]

Posted in golang, packages, sync

Leave a Reply

Your email address will not be published. Required fields are marked *