Sobes.tech
Senior

What thread-safe data structures do you know in Go?

sobes.tech AI

Answer from AI

The Go standard library provides several thread-safe structures and primitives for concurrency:

  • sync.Mutex and sync.RWMutex — for protecting access to regular data structures.
  • sync.Map — a thread-safe map optimized for frequent read and write operations.
  • Channels (chan) — allow safe data exchange between goroutines.
  • sync.WaitGroup — for synchronizing the completion of multiple goroutines.

Example of using sync.Map:

var m sync.Map

// Store
m.Store("key", "value")

// Load
if val, ok := m.Load("key"); ok {
    fmt.Println(val)
}

Additionally, for thread-safe queues or other structures, third-party libraries are often used or custom implementations are created using mutexes and channels.

What thread-safe data structures do you know in Go… - sobes.tech