Junior — Middle
Kas kasite omaatsed operatsioone oma projektides?
sobes.tech AI
Vastus AI-lt
In Go, atomic operations are used for safe modification of variables in a concurrent environment without using mutexes. For example, the sync/atomic package provides functions for atomic increment, compare, and swap of values.
Example of atomic increment of a counter:
import (
"fmt"
"sync/atomic"
)
var counter int64
func increment() {
atomic.AddInt64(&counter, 1)
}
func main() {
increment()
fmt.Println(atomic.LoadInt64(&counter)) // Will print 1
}
Using atomic operations helps prevent race conditions when working with simple data types, ensuring high performance without locks.