Junior — Middle
What events and signals can be used to interact with goroutines in the Go language?
sobes.tech AI
Answer from AI
In the Go language, the following main mechanisms are used for interaction with goroutines:
- Channels — the primary way to transmit data and signals between goroutines. Through channels, you can send and receive values, which allows synchronization.
ch := make(chan int)
go func() {
ch <- 42 // send value
}()
val := <-ch // receive value
- Context (context.Context) — used to manage the lifetime of goroutines, cancel operations, and pass cancellation signals.
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
select {
case <-ctx.Done():
// handle cancellation
}
}(ctx)
cancel() // cancellation signal
-
sync.WaitGroup — for waiting for a group of goroutines to finish.
-
OS signals — through the
os/signalpackage, system signals can be caught and passed to goroutines for proper termination.
Thus, the main "events" for interaction are send/receive operations on channels, cancellation via context, and system signals.