Middle+
What are atomic operations in Go?
sobes.tech AI
Answer from AI
Atomic operations in Go are operations that are executed entirely or not at all, without the possibility of interruption or interference from other goroutines. They ensure safe modification of shared data without using locks.
In the sync/atomic package, there are functions for atomic reading, writing, and modifying values, for example:
import (
"fmt"
"sync/atomic"
)
func main() {
var counter int64 = 0
atomic.AddInt64(&counter, 1) // atomically increment the counter
fmt.Println(atomic.LoadInt64(&counter)) // atomically read the value
}
This is important for concurrent programs to avoid data races and ensure correctness.