×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to add value to a 64-bit unsigned integer in an uninterruptible manner

Here, we are going to learn how to add value to a 64-bit unsigned integer in an uninterruptible manner in Golang (Go Language)?
Submitted by Nidhi, on May 03, 2021 [Last updated : March 05, 2023]

Adding value to a 64-bit unsigned integer in an uninterruptible manner in Golang

Problem Solution:

Here, we will perform the addition of a number with a 64-bit unsigned integer in a synchronized manner. Here, we will use atomic.AddUint64() function. The atomic.AddUint64() function is used in synchronized manner for multithreaded/multi-process environment.

Program/Source Code:

The source code to add value to a 64-bit unsigned integer in an uninterruptible manner is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

Golang code to add value to a 64-bit unsigned integer in an uninterruptible manner

// Golang program to add value to a 64-bit unsigned integer
// in an uninterruptible manner

package main

import "fmt"
import "sync/atomic"

// Entry point of the program
func main() {
	var num1 uint64 = 123457203685477580
	var num2 uint64 = 543217203685477580

	res1 := atomic.AddUint64(&num1, 50)
	res2 := atomic.AddUint64(&num2, 70)

	fmt.Println("Result1: ", res1)
	fmt.Println("Result2: ", res2)
}

Output:

Result1:  123457203685477630
Result2:  543217203685477650

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the required packages to predefined functions.

In the main() function, we created two 64-bit unsigned integer variables. Then we added the values to the variables using the atomic.AddUint64() function one by one. After that, we printed the result on the console screen.

Golang sync/atomic Package Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.