Menu Close

Go – SwapPointer() in sync/atomic package

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

The SwapPointer function is part of the “sync/atomic” package in Go, which supplies low-level atomic memory operations. This function atomically swaps the value of a pointer 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:

Syntax:

func SwapPointer(addr *unsafe.Pointer, newVal unsafe.Pointer) (oldVal unsafe.Pointer)

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

Example

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

package main

import (

	"fmt"

	"sync"

	"sync/atomic"

	"time"

	"unsafe"

)


type Data struct {

	Value int

}


func main() {

	data := []*Data{{0}, {1}, {2}, {3}, {4}}

	var sharedPointer unsafe.Pointer = unsafe.Pointer(data[0])

	var wg sync.WaitGroup


	// Swapper goroutine
	wg.Add(1)

	go func() {

		defer wg.Done()

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

			oldPointer := atomic.SwapPointer(&sharedPointer, unsafe.Pointer(data[i]))

			fmt.Printf("Swapper: Shared pointer set to %p (was %p)\n", data[i], oldPointer)

			time.Sleep(time.Millisecond * 500)

		}

	}()


	// Reader goroutine
	wg.Add(1)

	go func() {

		defer wg.Done()

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

			currentPointer := (*Data)(atomic.LoadPointer(&sharedPointer))

			fmt.Printf("Reader: Current pointer value is %p (Value: %d)\n", currentPointer, currentPointer.Value)

			time.Sleep(time.Millisecond * 250)

		}

	}()


	wg.Wait()

}

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

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

Conclusion

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

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 *