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
Mutexfor locking critical sections,RWMutexfor separating read and write locks, andWaitGroupfor 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.