Junior — Middle
How is control over the execution and synchronization of goroutines implemented in a program?
sobes.tech AI
Answer from AI
In Go, control over goroutine execution and synchronization is usually achieved using:
- WaitGroup from the
syncpackage — allows waiting for a group of goroutines to finish. - Channels — used for passing data and signals between goroutines, providing synchronization.
Example with WaitGroup:
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// goroutine work
}()
wg.Wait() // wait for the goroutine to finish
Channels, for example, allow passing results or completion signals:
ch := make(chan int)
go func() {
ch <- 42 // send value
}()
value := <-ch // receive value, synchronizing goroutines
Thus, WaitGroup and channels are the main tools for controlling and synchronizing goroutines.