Sobes.tech
Junior — Middle

Can you name lock-free data structures you know?

sobes.tech AI

Answer from AI

Lock-free data structures are structures that ensure correct operation in a multithreaded environment without using mutexes or other locks, which increases performance and reduces the risk of deadlocks.

In Go, several examples of such structures or approaches can be highlighted:

  • Atomic variables — using the sync/atomic package for atomic operations on primitive types (int, uint, pointer). For example, atomic increment of a counter.

  • Lock-free queues — implementations of queues based on atomic CAS (Compare-And-Swap) operations, such as the Michael-Scott queue.

  • Ring buffer with atomic indices — for passing data between goroutines without locks.

Example of an atomic counter:

import (
    "fmt"
    "sync/atomic"
)

func main() {
    var counter int64 = 0
    atomic.AddInt64(&counter, 1) // atomic increment
    fmt.Println(atomic.LoadInt64(&counter))
}

For more complex structures, specialized libraries are often used, as implementing lock-free structures is a non-trivial task.