Menu Close

Go – AddUint32 in sync/atomic package in Go

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

AddUint32 is a function that atomically adds a value to a uint32 variable and returns the new value. The function signature is as follows:

Syntax:

func AddUint32(addr *uint32, delta uint32) (new uint32)
  • addr: A pointer to the uint32 value that you want to add to.
  • delta: The uint32 value to be added to the value at addr.

The function returns the new value at addr after the addition is performed.

Example

Let’s consider an example to demonstrate the use of AddUint32. We’ll create a simple counter that can be incremented by multiple goroutines concurrently.

package main

import (

	"fmt"

	"sync"

	"sync/atomic"

)


var counter uint32


func main() {

	var wg sync.WaitGroup

	wg.Add(100)


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

		go func() {

			defer wg.Done()

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

				atomic.AddUint32(&counter, 1)
			}
		}()
	}


	wg.Wait()

	fmt.Println("Counter value:", counter)

}

In this example, we have a global counter variable, which is a uint32. We create 100 goroutines, and each goroutine increments the counter 1000 times. By using AddUint32, we ensure that the increment operation is atomic, and there are no race conditions between the goroutines.

Output:

Counter value: 100000

Conclusion

The AddUint32 function in the sync/atomic package is a powerful tool for managing shared resources in concurrent programming in Go. It allows you to atomically add a value to a uint32 variable, preventing race conditions and ensuring the integrity of your data. By understanding how to use AddUint32 and other atomic operations in the sync/atomic package, you can create more robust and efficient concurrent applications in Go.

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 *