Menu Close

Go – CompareAndSwapUint32() in atomic package

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

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


func CompareAndSwapUint32(addr *uint32, old, new uint32) (swapped bool)
  • addr: A pointer to the memory address storing the uint32 value that needs to be compared and potentially swapped.
  • old: The uint32 value that is expected to be stored at the memory address.
  • new: The uint32 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 CompareAndSwapUint32 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 CompareAndSwapUint32 function. Suppose we have a shared counter that multiple goroutines increment concurrently.

package main

import (





func main() {

	var counter uint32

	var wg sync.WaitGroup

	increment := func() {

		defer wg.Done()

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

			for {

				old := atomic.LoadUint32(&counter)

				new := old + 1

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







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

		go increment()



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


In this example, we have a uint32 counter variable that we want to increment atomically. We use the CompareAndSwapUint32 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 CompareAndSwapUint32 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 CompareAndSwapUint32 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 *