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:


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.


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 (





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) {







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

		go increment()



	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.


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:[email protected]

Posted in golang, packages, sync

Leave a Reply

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