Junior — Middle
Kuidas määrata, kas kõik kanalid on suletud Main meetodist?
sobes.tech AI
Vastus AI-lt
In Go, determining that all channels are closed from the main method can be done in several ways, depending on the context:
-
Use a channel to signal completion — for example, close a separate channel when all worker goroutines have finished.
-
Check for channel closure during read — when reading from a channel, the operator
v, ok := <-chreturnsok == falseif the channel is closed and all data has been read. -
Use
sync.WaitGroupto wait for all goroutines writing to the channel to finish, then close the channel inmainafter their completion.
Example with WaitGroup:
var wg sync.WaitGroup
ch := make(chan int)
wg.Add(1)
go func() {
defer wg.Done()
// work with the channel
ch <- 1
}()
// In a separate goroutine, close the channel after all senders are done
go func() {
wg.Wait()
close(ch)
}()
for v := range ch {
fmt.Println(v) // loop ends when the channel is closed
}
This way, in main, you can determine that the channel is closed when the loop over it ends, indicating that all data has been sent and the channel is closed.