Sobes.tech
Junior

Mis Go-s tagab thread-turvalisuse (thread safety)?

sobes.tech AI

Vastus AI-lt

Concurrency safety in Go is ensured through several mechanisms:

  • Goroutines — lightweight threads that allow code to run in parallel.
  • Channels — the main tool for safe data exchange between goroutines without using shared variables.
  • sync package — contains synchronization primitives such as Mutex for locking critical sections, RWMutex for separating read and write locks, and WaitGroup for waiting for a group of goroutines to finish.

Example of using a mutex to protect a shared resource:

import (
    "sync"
)

var mu sync.Mutex
var counter int

func increment() {
    mu.Lock()
    defer mu.Unlock()
    counter++
}

Thus, concurrency safety in Go is achieved through the proper use of goroutines, channels, and primitives from the sync package.