Menu Close

Go – CompareAndSwapUint64() in atomic package

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

The CompareAndSwapUint64 function is part of the sync/atomic package in Go. It performs an atomic compare-and-swap operation on a uint64 value. The function prototype is as follows:

Syntax:

func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)
  • addr: A pointer to the memory address storing the uint64 value that needs to be compared and potentially swapped.
  • old: The uint64 value that is expected to be stored at the memory address.
  • new: The uint64 value that will replace the old value if the comparison is successful.
  • Return value: swapped: A boolean value that indicates whether the swap was successful (true) or not (false).

The CompareAndSwapUint64 function performs an atomic operation, ensuring that the comparison and swap occur without being interrupted by other goroutines. This is essential when working with shared memory in concurrent code.

Example

Let’s consider a simple example to demonstrate the use of the CompareAndSwapUint64 function. Suppose we have a shared counter that multiple goroutines increment concurrently.

package main


import (

	"fmt"

	"sync"

	"sync/atomic"

)


func main() {

	var counter uint64

	var wg sync.WaitGroup


	increment := func() {

		defer wg.Done()

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

			for {

				old := atomic.LoadUint64(&counter)

				new := old + 1

				if atomic.CompareAndSwapUint64(&counter, old, new) {

					break

				}

			}

		}

	}


	wg.Add(5)


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

		go increment()

	}


	wg.Wait()


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

}

In this example, we have a uint64 counter variable that we want to increment atomically. We use the CompareAndSwapUint64 function to ensure that the counter is incremented safely by multiple goroutines. Each goroutine attempts to increment the counter 1,000 times. With five goroutines running concurrently, the expected final value of the counter is 5,000.

Conclusion

The CompareAndSwapUint64 function in Go’s sync/atomic package provides a low-level atomic operation for safe access and modification of shared memory in concurrent code. When working with shared memory in concurrent programming, it is essential to use atomic operations to avoid data races and ensure data consistency. This article has provided a detailed explanation of the CompareAndSwapUint64 function and demonstrated its usage through an example.

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 *