Menu Close

Go – LoadUintptr() in sync/atomic package

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

The LoadUintptr function in go is a member of the “sync/atomic” package in Go which supplies low-level atomic memory operations. This function atomically loads and returns the current value of a uintptr variable. It is a read operation that ensures the value read is the most recent one written by another concurrent thread. The function signature is as follows:

Syntax:

func LoadUintptr(addr *uintptr) uintptr

The function takes a pointer to a uintptr variable addr as an argument and returns the current value of the variable.

Example

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

package main


import (

	"fmt"

	"sync"

	"sync/atomic"

	"time"

)


func main() {

	var counter uintptr = 0

	var wg sync.WaitGroup


	// Incrementer goroutine
	wg.Add(1)

	go func() {

		defer wg.Done()

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

			atomic.AddUintptr(&counter, 1)

			time.Sleep(time.Millisecond)

		}

	}()


	// Reader goroutine
	wg.Add(1)

	go func() {

		defer wg.Done()

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

			fmt.Printf("Current counter value: %d\n", atomic.LoadUintptr(&counter))

			time.Sleep(time.Millisecond * 100)

		}

	}()


	wg.Wait()

}

In this example, we use the sync.WaitGroup to ensure that both goroutines complete before the program exits. The incrementer goroutine increments the counter using the atomic.AddUintptr function, which performs an atomic addition. Meanwhile, the reader goroutine reads the counter value using the atomic.LoadUintptr function, guaranteeing that it always reads the latest value written by the incrementer goroutine.

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

Conclusion

The LoadUintptr function is a vital utility provided by the sync/atomic package in Go, enabling atomic read operations on uintptr variables. It is especially useful in concurrent programming when multiple goroutines access shared memory. Using the LoadUintptr function ensures data consistency and helps to 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:

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 *