Junior — Senior
Preventing panic when dividing by zero
livecode
Task condition
It is necessary to modify the program so that a panic does not occur when dividing by zero. It is important to correctly synchronize goroutines and ensure that the channel resource is released regardless of the division result.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
wg := sync.WaitGroup{}
ch := make(chan struct{}, 5)
for i := 0; i < 10; i++ {
i := i
wg.Add(1)
go func() {
defer wg.Done()
printNumber(ch, i)
}()
}
wg.Wait()
close(ch)
}
func printNumber(ch chan struct{}, n int) {
ch <- struct{}{}
time.Sleep(time.Second)
if n != 0 {
fmt.Println(1 / n)
}
<-ch
}