Sobes.tech
Junior — Middle

Kuidas toimub suhtlus goroutine'ide vahel Go-s?

sobes.tech AI

Vastus AI-lt

In Go, the interaction between goroutines is carried out via channels. Channels allow safe data transfer between goroutines and synchronize their operation.

Main points:

  • The channel is created with make(chan Type).
  • Sending to the channel: ch <- value.
  • Receiving from the channel: value := <-ch.
  • Channels can be buffered or unbuffered.

Example:

func main() {
    ch := make(chan string)

    go func() {
        ch <- "hello from goroutine"
    }()

    msg := <-ch
    fmt.Println(msg)
}

Thus, channels provide safe and convenient interaction between parallel goroutines without the need to use mutexes or other locking mechanisms.