Menu Close

Go – LoadPointer() function in sync/atomic package

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

Introduction:

Concurrency is a key feature of the Go programming language, primarily achieved through goroutines and channels. However, in certain situations, low-level atomic operations are necessary for efficient concurrent code. The sync/atomic package in Go offers a set of functions for atomic memory access, including LoadPointer. In this article, we will discuss the LoadPointer function, its use cases, and provide a practical example.

What is LoadPointer Function ?

The LoadPointer function is part of the sync/atomic package in Go. It performs an atomic read operation on a pointer value. The function prototype is as follows:

Syntax:

func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)

Parameters:

  • addr: A pointer to the memory address storing the pointer value that needs to be read atomically.

Return Value:

  • val: The pointer value read from the memory address.

The LoadPointer function performs an atomic operation, ensuring that the read occurs 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 LoadPointer function. Suppose we have a shared pointer value that multiple goroutines read concurrently.

package main


import (

	"fmt"

	"sync"

	"sync/atomic"

	"unsafe"

)


type sharedStruct struct {

	value int

}


func main() {

	s := &sharedStruct{value: 100}

	sharedPointer := unsafe.Pointer(s)

	var wg sync.WaitGroup

	read := func(id int) {

		defer wg.Done()

		p := atomic.LoadPointer(&sharedPointer)

		sharedObj := (*sharedStruct)(p)

		fmt.Printf("Goroutine %d - Read value: %d\n", id, sharedObj.value)

	}


	wg.Add(5)


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

		go read(i)

	}


	wg.Wait()

}

In this example, we have a shared pointer to an instance of the sharedStruct type that we want to read atomically. We use the LoadPointer function to ensure that the shared pointer is read safely by multiple goroutines. Each goroutine reads the value from the shared object pointed to by the shared pointer.

Conclusion

The LoadPointer function in Go’s sync/atomic package provides a low-level atomic operation for safe access to 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 LoadPointer function and demonstrated its usage through an example.

To check more Go related articles. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

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 *