正在学习Go
,在此示例中,我可以看到该select
语句使goroutine等待多个通信操作
我们真的需要select
声明吗?我的下面做了同样的事情,没有select
声明
func runForChannel1(channel1 chan string) {
time.Sleep(1 * time.Second)
channel1 <- "Hi Arun ... I am Channel-1"
}
func runForChannel2(channel2 chan string) {
time.Sleep(2 * time.Second)
channel2 <- "Hi Arun ... I am Channel-2"
}
func testSelect() {
channel1 := make(chan string)
channel2 := make(chan string)
go runForChannel1(channel1)
go runForChannel2(channel2)
chval1, chval2 := <-channel1, <-channel2
fmt.Println(chval1, chval2)
}
func main() {
testSelect()
}
没有select
陈述,我能够等待两个渠道获得其价值...为什么我们需要Select
陈述?有人可以教育我吗?
我们真的需要一个select语句吗?
是。如果能够执行多个通道操作,则没有用户代码可以选择几种可能的通道操作之一;如果没有准备就绪,则用户代码不能选择任何一种(默认)。
(您的代码所做的事情完全不同。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句