Junior — Middle
What methods are used for data transfer when interacting between goroutines in Go?
sobes.tech AI
Answer from AI
In Go, the following main methods are used for communication between goroutines (lightweight threads):
- Channels — the primary and recommended method. Channels allow safe transmission of values between goroutines, providing synchronization and data exchange.
ch := make(chan int)
go func() {
ch <- 42 // send value to channel
}()
value := <-ch // receive value from channel
-
Shared variables with synchronization — using shared data with mutexes (
sync.Mutex) or other synchronization primitives to prevent race conditions. -
sync package — provides various tools for goroutine coordination, such as
WaitGroup,Cond.
However, in Go, it is customary to avoid shared memory access and prefer data passing through channels, which simplifies development and enhances safety.