Sobes.tech
Junior — Middle

How is competition for data eliminated when working with goroutines in Go?

sobes.tech AI

Answer from AI

In Go, competition for data during parallel execution of goroutines is eliminated using several mechanisms:

  1. Mutexes (sync.Mutex) — allow blocking access to shared data so that only one goroutine can modify it at a time.
var mu sync.Mutex
var counter int

func increment() {
    mu.Lock()
    defer mu.Unlock()
    counter++
}
  1. Channels — enable safe data transfer between goroutines without explicit locking, implementing the CSP (Communicating Sequential Processes) model.
ch := make(chan int)

func worker() {
    val := <-ch // receive data
    // process val
}

func main() {
    go worker()
    ch <- 42 // send data
}
  1. sync/atomic package — for atomic operations on variables (e.g., incrementing a counter) without locks.

Thus, Go offers both low-level synchronization primitives and high-level channels for safe work with shared data in parallel goroutines.

How is competition for data eliminated when working… - sobes.tech