Menu Close

Go – AddInt64 in sync/atomic package in Go

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

The AddInt64 function is a part of the sync/atomic package, and it performs an atomic addition operation on a specified int64 value. This means that the addition is performed in such a way that it is guaranteed to be completed without being interrupted by other goroutines, ensuring data consistency.

Syntax:

func AddInt64(addr *int64, delta int64) (new int64)
  • addr: A pointer to the int64 value that you want to modify atomically.
  • delta: The value to be added to the int64 value pointed to by addr.
  • Returns the new value stored at the addr after performing the atomic addition.

Example

To demonstrate the usage of AddInt64, let’s consider a simple example. Imagine we want to implement a counter that can be incremented concurrently by multiple goroutines without causing any race conditions. Using the AddInt64 function, we can achieve this as follows:

package main

import (

	"fmt"
	"sync"
	"sync/atomic"

)


func main() {

	var counter int64

	var wg sync.WaitGroup

	// Number of goroutines
	numGoroutines := 100

	wg.Add(numGoroutines)

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

		go func() {

			defer wg.Done()

			atomic.AddInt64(&counter, 1)

		}()
	}

	wg.Wait()

	fmt.Printf("Counter value: %d\n", counter)

}

In this example, we have a shared counter variable that is accessed and incremented by 100 goroutines concurrently. By using the AddInt64 function, we ensure that the increments are atomic, which guarantees that the final value of the counter is accurate and consistent.

Benefits of AddInt64:

  1. Thread safety: The atomic nature of the AddInt64 function ensures that shared data remains consistent and accurate when accessed by multiple goroutines.
  2. Performance: Atomic operations are generally faster than using locks or other synchronization primitives, making AddInt64 a more efficient option in certain scenarios.
  3. Simplicity: The sync/atomic package provides an easy-to-use interface for atomic operations, which simplifies concurrent programming.

Conclusion

The AddInt64 function in the sync/atomic package is an essential tool for writing efficient, thread-safe code 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 *