Junior — Middle
How is coordination of multiple goroutines in Go achieved?
sobes.tech AI
Answer from AI
In Go, coordination of multiple goroutines is usually achieved using channels and the sync package.
- Channels allow goroutines to exchange data and synchronize execution by blocking the sender or receiver until ready.
- sync.WaitGroup is used to wait for a group of goroutines to finish.
- Mutex and other primitives from sync provide safe access to shared resources.
Example of using a channel for synchronization:
ch := make(chan int)
go func() {
// Perform work
ch <- 1 // signal completion
}()
<-ch // wait for signal
Thus, channels and synchronization primitives enable efficient coordination of parallel tasks.