Sobes.tech
Senior

What will the program output? Why? ```go func main() { timeStart := time.Now() _, _ = <-worker(), <-worker() println(int(time.Since(timeStart).Seconds())) } func worker() chan int { ch := make(chan int) go func() { time.Sleep(3 * time.Second) ch <- 1 }() return ch } ```

sobes.tech AI

Answer from AI

The program will output 3.

Explanation:

  • The worker() function creates a channel ch and starts a goroutine that sleeps for 3 seconds, then sends the number 1 into the channel.
  • In main, <-worker() is called twice, creating two independent goroutines, each sleeping for 3 seconds and sending a value into its channel.
  • The statement _, _ = <-worker(), <-worker() reads from both channels sequentially, but both channels are already running in parallel, and both goroutines sleep simultaneously.
  • Therefore, the total waiting time is about 3 seconds, not 6.

The output println(int(time.Since(timeStart).Seconds())) converts the elapsed time to seconds and prints an integer, so the result is 3.