Menu Close

Go – SwapInt64() in sync/atomic package

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

The SwapInt64 function is part of the “sync/atomic” package in Go, which supplies low-level atomic memory operations. This function atomically swaps the value of an int64 variable with a new value. It is a read-modify-write operation that ensures the value written is immediately visible to other concurrent threads. The function signature is as follows:


func SwapInt64(addr *int64, newVal int64) (oldVal int64)

The function takes a pointer to an int64 variable addr and an int64 value newVal as arguments. It atomically sets the value of addr to newVal and returns the previous value stored in addr.


To illustrate the usage of the SwapInt64 function, let’s create a simple program simulating concurrent data access. We will create two goroutines: one that swaps a shared counter with a new value using the SwapInt64 function and another that reads and prints the counter value using the atomic.LoadInt64 function.

package main

import (






func main() {

	var counter int64 = 0

	var wg sync.WaitGroup

	// Swapper goroutine

	go func() {

		defer wg.Done()

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

			oldVal := atomic.SwapInt64(&counter, int64(i+1))

			fmt.Printf("Swapper: Counter set to %d (was %d)\n", i+1, oldVal)

			time.Sleep(time.Millisecond * 500)



	// Reader goroutine

	go func() {

		defer wg.Done()

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

			fmt.Printf("Reader: Current counter value is %d\n", 

			time.Sleep(time.Millisecond * 250)





In this example, we use the sync.WaitGroup to ensure that both goroutines complete before the program exits. The swapper goroutine sets the counter value using the atomic.SwapInt64 function and prints the old value, ensuring atomicity. Meanwhile, the reader goroutine reads the counter value using the atomic.LoadInt64 function, guaranteeing that it always reads the latest value written by the swapper goroutine.

This example demonstrates how the SwapInt64 function can be used to perform atomic swap operations on a shared int64 variable, ensuring data consistency across concurrent threads.


The SwapInt64 function is a valuable utility provided by the sync/atomic package in Go, enabling atomic swap operations on int64 variables. It is particularly useful in concurrent programming when multiple goroutines access shared memory. Using the SwapInt64 function ensures data consistency and helps eliminate race conditions, contributing to the overall stability and reliability of your concurrent Go applications.

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 *