Sobes.tech
Middle

How can goroutines communicate with each other? What synchronization methods exist in Go?

sobes.tech AI

Answer from AI

Goroutines in Go can communicate with each other using channels. Channels allow passing values between goroutines, ensuring synchronization and data exchange.

Main synchronization methods in Go:

  • Channels — enable safe data transfer between goroutines and automatically synchronize them.
  • Mutex (sync.Mutex) — used to protect shared resources from concurrent access.
  • WaitGroup (sync.WaitGroup) — helps wait for a group of goroutines to finish.
  • Cond (sync.Cond) — conditional variables for more complex synchronization.

Example of using a channel for communication between goroutines:

package main

import (
    "fmt"
    "time"
)

func worker(ch chan string) {
    time.Sleep(time.Second)
    ch <- "done"
}

func main() {
    ch := make(chan string)
    go worker(ch)
    msg := <-ch
    fmt.Println("Goroutine work:", msg)
}
How can goroutines communicate with each other? What… - sobes.tech