Función atomic.StoreUint64() en Golang con ejemplos

En el lenguaje Go, los paquetes atómicos proporcionan una memoria atómica de nivel inferior que es útil para implementar algoritmos de sincronización. La función StoreUint64() en el lenguaje Go se usa para almacenar atómicamente val en *addr . Esta función se define en el paquete atómico. Aquí, debe importar el paquete «sync/atomic» para usar estas funciones.

Sintaxis:

func StoreUint64(addr *uint64, val uint64)

Aquí, addr indica dirección.

Nota: (*uint64) es el puntero a un valor uint64. Y uint64 es un tipo entero de tamaño de bit 64. Sin embargo, int64 contiene el conjunto de todos los enteros de 64 bits sin signo de 0 a 18446744073709551615.

Valor de retorno: almacena el valor en *addr y luego se puede devolver cuando sea necesario.

Ejemplo 1:

// Program to illustrate the usage of
// StoreUint64 function in Golang
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Defining variables for the
    // address to store the val
    var (
        x uint64
        y uint64
    )
  
    // Using StoreUint64 method
    // with its parameters
    atomic.StoreUint64(&x, 56576656555555)
    atomic.StoreUint64(&y, 0)
  
    // Displays the value
    // stored in addr
    fmt.Println(atomic.LoadUint64(&x))
    fmt.Println(atomic.LoadUint64(&y))
}

Producción:

56576656555555
0

Aquí, primero, el valor uint64 se almacena en las direcciones definidas y luego se devuelven utilizando el método LoadUint64() anterior.

Ejemplo 2:

// Program to illustrate the usage of
// StoreUint64 function in Golang
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Defining variables for
    // the address to store the val
    var (
        x uint64
    )
  
    // Using StoreUint64 method
    // with its parameters
    atomic.StoreUint64(&x, 111776540544)
  
    // Loading the stored val
    z := atomic.LoadUint64(&x)
  
    // Prints true if values
    // are same else false
    fmt.Println(z == x)
  
    // Prints true if addresses 
    // are same else false
    fmt.Println(&z == &x)
}

Producción:

true
false

Aquí, el valor almacenado y cargado es el mismo, por lo que se devuelve verdadero, pero sus direcciones no son las mismas, por lo que se devuelve falso en ese caso.

Publicación traducida automáticamente

Artículo escrito por nidhi1352singh y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *