Sobes.tech
Middle

How do atomic operations work?

sobes.tech AI

Answer from AI

Atomic operations are operations that are executed entirely or not at all, without intermediate states visible to other threads.

In Go, the sync/atomic package provides functions to perform such operations on variables (e.g., AddInt32, CompareAndSwapInt64). This allows safe modification of values in a concurrent environment without using mutexes.

Example:

import (
    "fmt"
    "sync/atomic"
)

func main() {
    var counter int32 = 0
    atomic.AddInt32(&counter, 1) // atomic increment by 1
    fmt.Println(counter) // 1
}

Atomicity guarantees that the operation will not be interrupted and other goroutines will see either the old or the new value, but not an intermediate one.

How do atomic operations work? — Golang - sobes.tech