Menu Close

Go – CompareAndSwapInt32 in atomic package

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

The CompareAndSwapInt32 function is part of the sync/atomic package and is used to perform an atomic compare-and-swap operation on a shared int32 value. The function prototype is as follows:

Syntax:

func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)
  • addr: A pointer to the int32 value that needs to be updated.
  • old: The expected current value of the int32.
  • new: The new value that should replace the current value.

The function returns a boolean value (swapped) indicating if the swap was successful. If the current value at addr matches the old value, the function atomically replaces the current value with the new value and returns true. If the current value does not match the old value, no operation is performed, and the function returns false.

Example

Let’s see an example of using CompareAndSwapInt32 in practice. Consider a simple counter that needs to be incremented concurrently by multiple goroutines:

package main


import (

	"fmt"

	"sync"

	"sync/atomic"

)


var counter int32


func main() {

	var wg sync.WaitGroup

	wg.Add(10)


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

		go func() {

			defer wg.Done()


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

				incrementCounter()

			}

		}()

	}


	wg.Wait()

	fmt.Println("Final counter value:", counter)

}


func incrementCounter() {

	for {

		current := atomic.LoadInt32(&counter)

		new := current + 1


		if atomic.CompareAndSwapInt32(&counter, current, new) {

			break

		}

	}

}

In this example, we have a shared counter variable, and ten goroutines are trying to increment the counter 1,000 times each. To ensure that the counter is incremented safely and atomically, we use the incrementCounter function, which utilizes CompareAndSwapInt32.

In the incrementCounter function, we first load the current value of the counter using atomic.LoadInt32. We then calculate the new value by adding 1 to the current value. Finally, we use CompareAndSwapInt32 to atomically update the counter if its current value matches the expected old value. If the swap fails (due to a concurrent update by another goroutine), we retry the operation in a loop until it succeeds.

Conclusion

CompareAndSwapInt32 is a powerful atomic operation provided by Go’s sync/atomic package, which helps developers handle concurrent access to shared int32 values. By understanding and utilizing this function correctly, you can prevent race conditions and other synchronization issues in your concurrent Go applications.

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

https://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 *