chan1 and chan2 of type chan stringdone of type chan bool to signal when to stopselect statement inside a for loop to receive messages from chan1 and chan2fmt.Printlntrue to donechan1 and chan2 of type chan stringdone of type chan bool to signal when to stopselect statement inside a for loop to receive messages from chan1 and chan2fmt.Printlntrue to donechan1 and chan2 of type chan string.Use make(chan string) to create a channel of strings.
done of type chan bool to signal when to stop the program.Use make(chan bool) to create the done channel.
for loop with a select statement to receive messages from chan1 and chan2. Use variables msg1 and msg2 to receive messages. Count the total messages received in a variable called count.Use select inside a for loop to wait for messages from both channels.
chan1 and chan2 using fmt.Println. Stop the loop after receiving 2 messages and send true to done. Also, add a line to receive from done to prevent the program from exiting early.Use <-done to wait for the done signal before exiting.
What does the select statement do when used with multiple channels in Go?
select statement waits for one of its channel cases to be ready.Which of the following is the correct syntax to use select with two channels ch1 and ch2 for receiving values?
?
val := <-ch to assign the received value.val := <-ch1.What will be the output of the following Go program?
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(100 * time.Millisecond)
ch1 <- "hello"
}()
go func() {
time.Sleep(50 * time.Millisecond)
ch2 <- "world"
}()
select {
case msg1 := <-ch1:
fmt.Println(msg1)
case msg2 := <-ch2:
fmt.Println(msg2)
}
}ch2 sleeps 50ms, and ch1 sleeps 100ms.ch2 sends first, the select will receive from ch2 and print "world".Identify the error in this Go code using select with multiple channels:
package main
import "fmt"
func main() {
ch1 := make(chan int)
ch2 := make(chan int)
select {
case val := <-ch1:
fmt.Println(val)
case val := <-ch2:
fmt.Println(val)
}
}ch1 and ch2 are unbuffered with no goroutines to send values.select blocks forever since no channels become ready, causing a deadlock.You want to write a Go function that waits on two channels chA and chB and returns the first value received from either. If neither channel is ready immediately, it should return "timeout" after 100 milliseconds. Which select structure correctly implements this?
time.After function returns a channel that sends a value after the specified duration, perfect for timeout.chA and chB return the first received value; the timeout case returns "timeout" after 100ms.Pass the test and this pattern moves unknown