Sobes.tech
Junior — Middle

Millised andmeedastusmeetodid kasutatakse Go-s goroutine'ide vahelise suhtluse ajal?

sobes.tech AI

Vastus AI-lt

In Go, the main ways of communication between goroutines (lightweight threads) are:

  1. Channels — the primary and recommended method. Channels allow safe transmission of values between goroutines, ensuring synchronization and data exchange.
ch := make(chan int)
go func() {
    ch <- 42 // sending value to the channel
}()
value := <-ch // receiving value from the channel
  1. Shared variables with synchronization — using shared data with mutexes (sync.Mutex) or other synchronization primitives to prevent race conditions.

  2. sync package — provides various tools for coordinating goroutines, such as WaitGroup, Cond.

However, in Go, it is common to avoid shared memory access and prefer transmitting data via channels, which simplifies development and increases safety.