Sobes.tech
Junior — Middle

Explain the principle of the goroutine synchronization mechanism in the context of concurrent task execution.

sobes.tech AI

Answer from AI

In Go, goroutines are lightweight threads that execute concurrently. Mechanisms are used to synchronize goroutines, allowing coordination of access to shared resources and ordering of execution.

Main synchronization mechanisms:

  • Channels: allow data transfer between goroutines, ensuring synchronization through message exchange.
  • Mutexes (sync.Mutex): block access to shared data to prevent race conditions.
  • WaitGroup (sync.WaitGroup): allows waiting for a group of goroutines to finish.

Example with a channel:

package main

import (
    "fmt"
)

func worker(ch chan int) {
    val := <-ch // wait for data from the channel
    fmt.Println("Received value:", val)
}

func main() {
    ch := make(chan int)
    go worker(ch)
    ch <- 42 // send data into the channel
}

Here, the channel provides synchronization: the worker goroutine waits until main sends a value.