Menu Close

Go – LoadInt32() function in sync/atomic package

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

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

Syntax:

func LoadInt32(addr *int32) (val int32)

Parameters:

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

Return Value:

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

The LoadInt32 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 LoadInt32 function. Suppose we have a shared int32 value that multiple goroutines read concurrently.

package main


import (

	"fmt"

	"sync"

	"sync/atomic"

	"time"

)


func main() {

	var sharedValue int32 = 100

	var wg sync.WaitGroup


	read := func(id int) {

		defer wg.Done()

		time.Sleep(time.Duration(id) * 10 * time.Millisecond)

		val := atomic.LoadInt32(&sharedValue)

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

	}


	wg.Add(5)


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

		go read(i)

	}


	wg.Wait()

}

In this example, we have an int32 sharedValue variable that we want to read atomically. We use the LoadInt32 function to ensure that the sharedValue is read safely by multiple goroutines. Each goroutine sleeps for a specific duration before reading the value, simulating a real-world scenario where goroutines perform work before accessing the shared memory.

Conclusion

The LoadInt32 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 LoadInt32 function and demonstrated its usage through an example.

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 *