What methods are used to control and coordinate goroutine work in Go?
sobes.tech AI
Answer from AI
In Go, control and coordination of goroutine work are carried out in several ways:
-
Channels — the main mechanism for data exchange and synchronization between goroutines. Channels allow safe transfer of values and block the sender or receiver until ready.
-
sync.WaitGroup — used to wait for a group of goroutines to finish. It allows the main goroutine to wait until all launched goroutines complete.
-
Context (context.Context) — used to manage the lifetime of goroutines, pass cancellation signals, and deadlines.
-
Mutexes and other primitives from the sync package — for protecting shared resources and preventing data races.
Example with WaitGroup and channel:
var wg sync.WaitGroup
ch := make(chan int)
wg.Add(1)
go func() {
defer wg.Done()
ch <- 42 // send value
}()
go func() {
val := <-ch // receive value
fmt.Println(val)
}()
wg.Wait() // wait for completion
Thus, the combination of channels and synchronization primitives allows efficient management of goroutine parallel execution.