Home >Backend Development >Golang >When and Why Should You Use `atomic.LoadInt64` in Go?
Atomic LoadInt32/StoreInt32 (64)
Atomic memory operations guarantee that conflicting accesses to a shared variable from multiple goroutines occur in a defined order, ensuring data consistency. The sync/atomic package provides atomic load and store operations for various data types, including int32 and int64.
Understanding the Difference
Both int64(&sharedA) and atomic.LoadInt64(&sharedA) perform atomic loads. However, the latter explicitly uses the sync/atomic package to ensure memory ordering. This is important when accessing shared variables that may be concurrently modified by multiple goroutines.
Using LoadInt64 ensures that:
Example Usage
Atomic loads and stores are commonly used in scenarios where:
Consider the following example:
<code class="go">package main import "sync/atomic" func main() { // Shared variables var sharedA int64 var sharedB *int64 // Concurrent code go func() { // Set sharedA to 10 atomic.StoreInt64(&sharedA, 10) }() go func() { // Set sharedB to a new value sharedB = new(int64) *sharedB = 20 }() // Main goroutine reads shared variables tmpVarA := atomic.LoadInt64(&sharedA) tmpVarB := atomic.LoadInt64(sharedB) // Print the values println(tmpVarA, *tmpVarB) }</code>
In this example, the StoreInt64 operation ensures that multiple goroutines concurrently modify sharedA and sharedB without causing data races. The LoadInt64 ensures that the main goroutine consistently reads the latest values from these shared variables.
The above is the detailed content of When and Why Should You Use `atomic.LoadInt64` in Go?. For more information, please follow other related articles on the PHP Chinese website!