Menu Close

Go – LoadUint32() in sync/atomic package

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

The LoadUint32 function belongs to the “sync/atomic” package in Go, which provides low-level atomic memory operations. This function loads and returns the current value of a uint32 variable atomically. It is a read operation that guarantees that the value read is the latest value written by another concurrent thread. The function signature is as follows:

Syntax:

func LoadUint32(addr *uint32) uint32

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

Example

To demonstrate the usage of the LoadUint32 function, let’s create a simple program that simulates 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 LoadUint32 function.

package main


import (

	"fmt"

	"sync"

	"sync/atomic"

	"time"

)


func main() {

	var counter uint32 = 0

	var wg sync.WaitGroup


	// Incrementer goroutine
	wg.Add(1)

	go func() {

		defer wg.Done()

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

			atomic.AddUint32(&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.LoadUint32(&counter))

			time.Sleep(time.Millisecond * 100)

		}

	}()


	wg.Wait()

}

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

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

Conclusion

The LoadUint32 function is an essential utility provided by the sync/atomic package in Go, enabling atomic read operations on uint32 variables. It is particularly useful in concurrent programming when multiple goroutines access shared memory. Using the LoadUint32 function ensures data consistency and eliminates 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://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 *