Junior — Senior
Determining the output of dividing 1 by n in a concurrent Go program
livecode
Task condition
It is necessary to understand what value will be printed by the program, where several goroutines call the function printNumber. Inside the function, a signal is sent to a buffered channel, there is a one-second pause, and the result of the expression 1 / n is printed. The program uses sync.WaitGroup to wait for all goroutines to finish and closes the channel after they are done.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
wg := sync.WaitGroup{}
ch := make(chan struct{}, 5)
for i := 0; i < 10; 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)
fmt.Println(1 / n)
<-ch
}